开发者

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

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[] 开发者_如何学PythonCars;
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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜