2

I have a multi-dim string array something like this:-

string[,] names = new string[2, 2] { {"Rosy",""}, {"Peter","Albert"} };

Now i want to check the existence if the second index (Albert) holding the string is non-empty in the whole array. I just to check the existence of the non-empty string value in the second index. I was thinking of using the Array.Exists. If there is any other better way, please share.

Thanks

2
  • Sorry, I can't really make sense of your question. Do you just want to know if there is a string "Albert" somewhere in the whole array? Commented Dec 16, 2010 at 7:32
  • "Albert" is an example. I just want to check if the second index contains empty string value or not. Commented Dec 16, 2010 at 7:36

1 Answer 1

2

I don't think you can use Array.Exists here, because that only deals with the values - you're interested in the position too. I would just use a loop:

bool found = false;
for (int i = 0; i < names.GetLength(0); i++)
{
    if (!string.IsNullOrEmpty(names[i, 1]))
    {
        found = true;
        break;
    }
}

Rectangular arrays are basically a bit of a pain to work with in C#. If you had a jagged array - an array of arrays - it would be easy:

bool found = jagged.Select(x => x[1])
                   .Any(value => !string.IsNullOrEmpty(value));
Sign up to request clarification or add additional context in comments.

3 Comments

It is not a jagged array. Can you provide something else. I want to avoid the for iteration.
@Karan: I know it's not a jagged array, which is why I provided the first method. I'm saying it would be easier as a jagged array, and suggesting that you reconsider your design. Something is going to have to iterate over the data, after all... and in this case, doing it yourself is likely to be the simplest approach if you've got to work with a rectangular array. You could always put this into a utility method somewhere, of course.
@Karan: What's wrong with the for iteration? Not fashionable?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.