Get index of object in a list using Linq [duplicate]

人盡茶涼 提交于 2019-12-17 23:09:56

问题


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.


回答1:


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

int index = customers.FindIndex(c => c.ID == 150);



回答2:


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.



来源:https://stackoverflow.com/questions/18108778/get-index-of-object-in-a-list-using-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!