How to get index using LINQ?

Posted by codymanix on Stack Overflow See other posts from Stack Overflow or by codymanix
Published on 2010-03-18T16:30:47Z Indexed on 2010/04/27 1:33 UTC
Read the original article Hit count: 478

Filed under:
|
|
|

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?

© Stack Overflow or respective owner

Related posts about LINQ

Related posts about c#