Distinct() with lambda?

前端 未结 18 970
南旧
南旧 2020-11-22 06:04

Right, so I have an enumerable and wish to get distinct values from it.

Using System.Linq, there\'s of course an extension method called Distinct<

18条回答
  •  醉话见心
    2020-11-22 06:46

    It looks to me like you want DistinctBy from MoreLINQ. You can then write:

    var distinctValues = myCustomerList.DistinctBy(c => c.CustomerId);
    

    Here's a cut-down version of DistinctBy (no nullity checking and no option to specify your own key comparer):

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

提交回复
热议问题