Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get index using LINQ? [duplicate]

Tags:

c#

.net

linq

c#-3.0

Given a datasource like that:

var c = new Car[] {   new Car{ Color="Blue", Price=28000},   new Car{ Color="Red", Price=54000},   new Car{ Color="Pink", Price=9999},   // .. }; 

How can I find the index of the first car satisfying a certain condition with LINQ?

EDIT:

I could think of something like this but it looks horrible:

int firstItem = someItems.Select((item, index) => new     {         ItemName = item.Color,         Position = index     }).Where(i => i.ItemName == "purple")       .First()       .Position; 

Will it be the best to solve this with a plain old loop?

like image 710
codymanix Avatar asked Mar 18 '10 16:03

codymanix


People also ask

How to get index of element in LINQ c#?

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

How to get duplicate records in LINQ c#?

The easiest way to solve the problem is to group the elements based on their value, and then pick a representative of the group if there are more than one element in the group. In LINQ, this translates to: var query = lst. GroupBy(x => x) .


1 Answers

myCars.Select((v, i) => new {car = v, index = i}).First(myCondition).index; 

or the slightly shorter

myCars.Select((car, index) => new {car, index}).First(myCondition).index; 

or the slightly shorter shorter

myCars.Select((car, index) => (car, index)).First(myCondition).index; 
like image 79
Yuriy Faktorovich Avatar answered Oct 19 '22 22:10

Yuriy Faktorovich