简体   繁体   中英

how to check all of the first and second elements of the 2D array?

how should I write this N ?

 int[,] spn = { { 3064, 22 }, { 3064, 16 }, { 3064, 11 } };

 if(spn[1, N] != 3064 && spn[N, 2] != 16 || spn[N, 2] != 16) 

spn[1, N] means all of the first items of the array. spn[N, 2] means all of the second items of the array.

You can iterate over the array with a for loop ( MSDN for (C# Reference)

      int[,] spn = { { 3064, 22 }, { 3064, 16 }, { 3064, 11 } };
      int helper = 2;
      for (var N = 0; N < spn.Length / helper; N++)
      {
          if (spn[N, 0] != 3064 && spn[N, 1] != 16 || spn[N, 1] != 16)
              System.Diagnostics.Debug.WriteLine("do something");
      }

As the array has only a absolute length, you save the number of arrayelements inside the helper variable. This only works for your sample with nested arrays of the same length.

You can you simple Loop:

 bool result = true;
 for (int i = 0; i < spn.GetLength(0); i++)
 {
    if (spn[i, 1] != 16 || spn[i, 2] != 16)
    {
       result = false;
       break;
    }
 }

Or you can use Linq to check all values:

bool result = Enumerable.Range(0, spn.GetLength(0)).All(i => spn[i, 1] != 16 || spn[i, 2] != 16);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM