【问题标题】:Get index of object in a list using Linq [duplicate]使用Linq获取列表中对象的索引[重复]
【发布时间】:2013-08-07 16:31:53
【问题描述】:

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

【问题讨论】:

    标签: linq list indexing find indexof


    【解决方案1】:

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

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

    【讨论】:

    • 不错,不知道这个方法
    • 太糟糕了,它没有被定义为 LINQ 方法,因此仅在使用真正的纯 List<T> 而不是任何 IList<T> 时才有用。
    • @O.R.Mapper 只需使用 .ToList().FindIndex() 即可将其应用于大多数 IEnumerables 或 ObservableCollections 到列表中
    • @Wilhelm:如果我正在寻找的元素可能在前几项中,我不喜欢评估整个枚举的想法。另外,请注意,在数组(可以从ToArray() 获得)也可以使用的情况下,从不有充分的理由使用ToList()
    【解决方案2】:

    Linq to Objects 已重载 Select 方法

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

    请记住,您应该拥有内存中的 List<Customer> 才能使用此 Linq to Objects 方法。

    【讨论】:

      猜你喜欢
      • 2020-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多