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.

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

If these are strings, why not use !string.IsNullOrEmpty(i)
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.