43

I am new to Linq. I have a Customers table.ID,FullName,Organization,Location being the columns. I have a query in Sqlite returning me 2500 records of customers. I have to find the index of the customer where ID=150 for example from this result set. Its a List of Customers. The result set of the query is ordered by organization. I tried with FindIndex and IndexOf but getting errors for the former and -1 for the latter. So, how should it be done? Thanks.

RookieAppler
  • 1,517
  • 5
  • 22
  • 58

2 Answers2

87

You don't need to use LINQ, you can use FindIndex of List<T>:

int index = customers.FindIndex(c => c.ID == 150);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 2
    Nice, didn't know about this method – Sergey Berezovskiy Aug 07 '13 at 16:41
  • 7
    Too bad this is not defined as a LINQ method and thus is only useful when working with a true pure `List` rather than any `IList`. – O. R. Mapper Feb 24 '14 at 22:10
  • 4
    You have also [`Array.FindIndex`](http://msdn.microsoft.com/en-us/library/03y7c6xy%28v=vs.110%29.aspx). – Tim Schmelter Nov 25 '14 at 23:41
  • @O.R.Mapper could apply this to most IEnumerables or ObservableCollections to a list by just using .ToList().FindIndex() – Wilhelm May 20 '20 at 09:18
  • 1
    @Wilhelm: I rather dislike the idea of evaluating the entire enumeration if the element I'm looking for might be among the first couple of items. Also, note that there is *never* a good reason to use `ToList()` in situations where an array (as can be obtained from `ToArray()`) would do as well. – O. R. Mapper May 20 '20 at 09:59
37

Linq to Objects has overloaded Select method

customers.Select((c,i) => new { Customer = c, Index = i })
         .Where(x => x.Customer.ID == 150)
         .Select(x => x.Index);

Keep in mind, that you should have in-memory List<Customer> to use this Linq to Objects method.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459