How to check if multidimensional array row contains non-Zero value

只谈情不闲聊 提交于 2019-12-11 20:39:41

问题


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:


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



来源:https://stackoverflow.com/questions/25562496/how-to-check-if-multidimensional-array-row-contains-non-zero-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!