代码之家  ›  专栏  ›  技术社区  ›  mezoid

如何使用Linq从对象列表中获取唯一的属性列表?

  •  159
  • mezoid  · 技术社区  · 16 年前

    我有一个MyClass类型的对象列表,这个类的属性之一是ID。

    public class MyClass
    {
      public int ID { get; set; }
    }
    

    IList<MyClass> 这样它返回一个 IEnumerable<int> 身份证号码?

    我确信使用LINQ在一行或两行中完成这项工作一定是可能的,而不是在MyClass列表中的每个项目中循环并将唯一值添加到列表中。

    4 回复  |  直到 3 年前
        1
  •  340
  •   Marc Gravell    16 年前
    IEnumerable<int> ids = list.Select(x=>x.ID).Distinct();
    
        2
  •  30
  •   Maksim Vi.    10 年前

    Distinct operator :

    var idList = yourList.Select(x=> x.ID).Distinct();
    
        3
  •  13
  •   Peter Mortensen icecrime    3 年前

    直接使用 LINQ ,与 Distinct()

    var idList = (from x in yourList select x.ID).Distinct();
    
        4
  •  3
  •   Peter Mortensen icecrime    3 年前
    int[] numbers = {1,2,3,4,5,3,6,4,7,8,9,1,0 };
    var nonRepeats = (from n in numbers select n).Distinct();
    
    foreach (var d in nonRepeats)
    {
    
        Response.Write(d);
    }
    

    输出

        5
  •  2
  •   Peter Mortensen icecrime    3 年前

    服用时 不同的 ,我们也必须投入到IEnumerable中。如果列表为<T>模型,这意味着您需要编写如下代码:

     IEnumerable<T> ids = list.Select(x => x).Distinct();