tags:

views:

116

answers:

4

I'm wondering if theres a method to determine whether a certain range of array elements is empty or not. for example, if the array was initialized with 10 elements having the values "", then if data was later assigned to elements 5, 7, 9; could i test if elements 0-3 were empty, or rather contained an empty string ""?

+5  A: 
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 in there.

Edit: made it Take(4) instead of 3 as per Jonathan's comment in the other answer (and now Guffa's comment in mine. ;) ).

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

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

So changed All to Any.

Kirk Woll
That only checks elements 0-2.
Guffa
ok i think this makes sense. But doesn't this only check if the entire range is blank? I guess I should have been more specific. Basically what I'm trying to do is determine if any of the elements in that range contain a blank
Sinaesthetic
@Sinaesthetic, modified answer, but use the `Any` operator instead of `All`.
Kirk Woll
+3  A: 
bool is0to3empty = myArrayOfString.Skip(0).Take(4).All(i => string.IsNullOrEmpty(i));
Rex M
SHouldn't that be Take(4)?
Jonathan Allen
@Jonathan yes but I don't think the exact number is really the question here.
Rex M
I worry that someone will see Take(3) and think it means "Take all the elements indexed up through 3".
Jonathan Allen
A: 

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

    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;
        }

    }
Aliostad
+1  A: 

The most straight forward and efficient would be to simply loop through that 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 would be to use extension methods to do the looping:

bool empty = theArray.Take(4).All(String.IsNullOrEmpty);
Guffa