0

Just a short question regarding multidimensional arrays in C#.

How can I check if one row of a multidimensional array contains a non-Zero value? In Matlab, the "any"-command does exactly what I need.

Finally I need to put the request into a while condition. Means in Matlab: while(any(array[1,2,:])) --> which means: while(any-entry-of-the-row-is-not-Zero)...

I tried already the Array.Exists() or Array.Find() but it seems to work only with one-dimensional arrays.

Thanks

2
  • show some code please ? i want to know the type of array ? Commented Aug 29, 2014 at 6:05
  • 1
    just a foreach and if statement would be enough. Commented Aug 29, 2014 at 6:05

1 Answer 1

2

You have a couple options

myMultiArray.Any(row => row.Contains(Something));

or as Sriram Sakthivel Suggested

foreach(var row in myMultiArray)
    if(row.Contains(Something)
        //Found it!

foreach(var row in myMultiArray)
    if(row.IndexOf(Something) >= 0)
        //Found it!

More spefically to your question

myMultiArray.Any(row => row.Any(cell => cell != 0));

foreach(var row in myMultiArray)
    foreach(var cell in myMultiArray)
        if(cell != 0)
            //Found it!

for(int i = 0; i < array.GetLength(0); i++)
    for(int j = 0; j < array.GetLength(1); j++)
         if(array[i,j] != 0)
             //Do Something

MSDN Information

Any

Contains

IndexOf

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the answer... Actually the Any command would be great, but I can't use it cause i generated a int[,,] array. I can use the foreach-possibility. I would have to work with List<List<int>> if I would like to use the C# Any-Command, right?
No worries, hope it helps
@Krus - The Any Command works on an IEnumerable which an array is, so no, you shouldn't need to use a list
With a one-dimensional array it works, but as soon as I change the array to an int[,] array, I can't use the Any-Command anymore...
@Krus - I got confused with 2d arrays and multidimentional ones earlier (had a coffee now!) I've attached some code that should do what you are looking for (without linq)

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.