How to get index using LINQ? [duplicate]

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?

7 Answers
7

Leave a Comment