Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to find array indexes of a value

Tags:

c#

linq

Assuming I have the following string array:

string[] str = new string[] {"max", "min", "avg", "max", "avg", "min"} 

Is it possbile to use LINQ to get a list of indexes that match one string?

As an example, I would like to search for the string "avg" and get a list containing

2, 4

meaning that "avg" can be found at str[2] and str[4].

like image 304
Dan Dinu Avatar asked Nov 08 '12 15:11

Dan Dinu


People also ask

How to get index in LINQ c#?

Simply do : int index = List. FindIndex(your condition);


2 Answers

.Select has a seldom-used overload that produces an index. You can use it like this:

str.Select((s, i) => new {i, s})     .Where(t => t.s == "avg")     .Select(t => t.i)     .ToList() 

The result will be a list containing 2 and 4.

Documentation here

like image 171
recursive Avatar answered Sep 19 '22 13:09

recursive


You can do it like this:

str.Select((v,i) => new {Index = i, Value = v}) // Pair up values and indexes    .Where(p => p.Value == "avg") // Do the filtering    .Select(p => p.Index); // Keep the index and drop the value 

The key step is using the overload of Select that supplies the current index to your functor.

like image 35
Sergey Kalinichenko Avatar answered Sep 21 '22 13:09

Sergey Kalinichenko