Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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.

like image 835
Magnum Avatar asked Mar 23 '11 04:03

Magnum


People also ask

What is C in used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

How do I use C on my computer?

It is a bit more cryptic in its style than some other languages, but you get beyond that fairly quickly. C is what is called a compiled language. This means that once you write your C program, you must run it through a C compiler to turn your program into an executable that the computer can run (execute).

Why do people use C?

The biggest advantage of using C is that it forms the basis for all other programming languages. The mid-level language provides the building blocks of Python, Java, and C++. It's a fundamental programming language that will make it easier for you to learn all other programming languages.

Is C still useful?

The C programming language has been alive and kicking since 1972, and it still reigns as one of the fundamental building blocks of our software-studded world.


1 Answers

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

like image 142
Ani Avatar answered Sep 25 '22 18:09

Ani