How to get index using LINQ?

codymanix picture codymanix · Mar 18, 2010 · Viewed 386.1k times · Source

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?

Answer

Yuriy Faktorovich picture Yuriy Faktorovich · Mar 18, 2010
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;