C #: is there a way to determine if a range of elements is empty?

I am wondering if there is a method to determine if a certain range of array elements is empty or not. for example, if the array was initialized with 10 elements having values โ€‹โ€‹", then, if subsequently the data was assigned to elements 5, 7, 9; can I check if elements 0-3 were empty or, rather, contain an empty string" "?

+4
source share
4 answers
array.Skip(startIndex).Take(count).All(x => string.IsNullOrEmpty(x)); 

So, if you are trying to check elements 0-3:

 array.Skip(0).Take(4).All(x => string.IsNullOrEmpty(x)); 

For clarity, I left Skip there.

Edit: made it Take(4) instead of 3 according to Jonathan's comments in another answer (and now Guffa's comment in mine .;)).

Edit 2: According to the comments below, the OP wanted to see if any of the elements matched:

 array.Skip(0).Take(4).Any(x => string.IsNullOrEmpty(x)); 

So All changed to Any .

+5
source
 bool is0to3empty = myArrayOfString.Skip(0).Take(4).All(i => string.IsNullOrEmpty(i)); 
+3
source

The most direct and efficient would be to simply skip this part of the array:

 bool empty = true;.. for (int i = 0; i <= 3; i++) { if (!String.IsNullOrEmpty(theArray[i])) { empty = false; break; } } if (empty) { // items 0..3 are empty } 

Another alternative could be to use extension methods to execute a loop:

 bool empty = theArray.Take(4).All(String.IsNullOrEmpty); 
+2
source

Create this extension class and you can call it from any array of strings:

  public static class IsEmptyInRangeExtension { public static bool IsEmptyInRange(this IEnumerable<string> strings, int startIndex, int endIndex) { return strings.Skip(startIndex).TakeWhile((x, index) => string.IsNullOrEmpty(x) && index <= endIndex).Count() > 0; } } 
+1
source

All Articles