LINQ: Distinct values

前端 未结 7 1309
一生所求
一生所求 2020-11-22 16:29

I have the following item set from an XML:

id           category

5            1
5            3
5            4
5            3
5            3
<
7条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 16:58

    Are you trying to be distinct by more than one field? If so, just use an anonymous type and the Distinct operator and it should be okay:

    var query = doc.Elements("whatever")
                   .Select(element => new {
                                 id = (int) element.Attribute("id"),
                                 category = (int) element.Attribute("cat") })
                   .Distinct();
    

    If you're trying to get a distinct set of values of a "larger" type, but only looking at some subset of properties for the distinctness aspect, you probably want DistinctBy as implemented in MoreLINQ in DistinctBy.cs:

     public static IEnumerable DistinctBy(
         this IEnumerable source,
         Func keySelector,
         IEqualityComparer comparer)
     {
         HashSet knownKeys = new HashSet(comparer);
         foreach (TSource element in source)
         {
             if (knownKeys.Add(keySelector(element)))
             {
                 yield return element;
             }
         }
     }
    

    (If you pass in null as the comparer, it will use the default comparer for the key type.)

提交回复
热议问题