11

I have an array of strings called "Cars"

I would like to get the first index of the array is either null, or the value stored is empty. This is what I got so far:

private static string[] Cars;
Cars = new string[10];
var result = Cars.Where(i => i==null || i.Length == 0).First(); 

But how do I get the first INDEX of such an occurrence?

For example:

Cars[0] = "Acura"; 

then the index should return 1 as the next available spot in the array.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Magnum
  • 1,555
  • 4
  • 18
  • 39

2 Answers2

17

You can use the Array.FindIndex method for this purpose.

Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the entire Array.

For example:

int index = Array.FindIndex(Cars, i => i == null || i.Length == 0);

For a more general-purpose method that works on any IEnumerable<T>, take a look at: How to get index using LINQ?.

Community
  • 1
  • 1
Ani
  • 111,048
  • 26
  • 262
  • 307
5

If you want the LINQ way of doing it, here it is:

var nullOrEmptyIndices =
    Cars
        .Select((car, index) => new { car, index })
        .Where(x => String.IsNullOrEmpty(x.car))
        .Select(x => x.index);

var result = nullOrEmptyIndices.First();

Maybe not as succinct as Array.FindIndex, but it will work on any IEnumerable<> rather than only arrays. It is also composable.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172