Alex Rivera | Logout

Using C# Linq to return first index of null/empty occurrence in an array

Asked 2011-03-23T04:28:05.633
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.

Edit
Report

1 Answer

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?.

answered 2011-03-23T04:31:26.377

Your Answer