list 使用 Linq 获取列表中对象的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18108778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 02:03:41  来源:igfitidea点击:

Get index of object in a list using Linq

linqlistindexingfindindexof

提问by RookieAppler

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.

我是 Linq 的新手。我有一个客户表。ID,FullName,Organization,Location 作为列。我在 Sqlite 中有一个查询,返回了 2500 条客户记录。例如,我必须从这个结果集中找到 ID=150 的客户索引。它的客户名单。查询的结果集按组织排序。我尝试使用 FindIndex 和 IndexOf 但前者出错,后者出错 -1。那么,应该怎么做呢?谢谢。

回答by Tim Schmelter

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

你并不需要使用LINQ,您可以使用FindIndexList<T>

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

回答by Sergey Berezovskiy

Linq to Objects has overloaded Selectmethod

Linq to Objects 重载了Select方法

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.

请记住,您应该在内存List<Customer>中使用此 Linq to Objects 方法。