How to check if multidimensional array row contain

2019-08-27 15:52发布

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

1条回答
祖国的老花朵
2楼-- · 2019-08-27 16:20

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

查看更多
登录 后发表回答