Why is there no Linq method to return distinct values by a predicate?

后端 未结 4 1117
一整个雨季
一整个雨季 2020-12-04 16:53

I want to get the distinct values in a list, but not by the standard equality comparison.

What I want to do is something like this:

return myList.Dis         


        
4条回答
  •  臣服心动
    2020-12-04 17:20

    It's annoying, certainly. It's also part of my "MoreLINQ" project which I must pay some attention to at some point :) There are plenty of other operations which make sense when acting on a projection, but returning the original - MaxBy and MinBy spring to mind.

    As you say, it's easy to write - although I prefer the name "DistinctBy" to match OrderBy etc. Here's my implementation if you're interested:

        public static IEnumerable DistinctBy
            (this IEnumerable source,
             Func keySelector)
        {
            return source.DistinctBy(keySelector,
                                     EqualityComparer.Default);
        }
    
        public static IEnumerable DistinctBy
            (this IEnumerable source,
             Func keySelector,
             IEqualityComparer comparer)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (keySelector == null)
            {
                throw new ArgumentNullException("keySelector");
            }
            if (comparer == null)
            {
                throw new ArgumentNullException("comparer");
            }
            return DistinctByImpl(source, keySelector, comparer);
        }
    
        private static IEnumerable DistinctByImpl
            (IEnumerable source,
             Func keySelector,
             IEqualityComparer comparer)
        {
            HashSet knownKeys = new HashSet(comparer);
            foreach (TSource element in source)
            {
                if (knownKeys.Add(keySelector(element)))
                {
                    yield return element;
                }
            }
        }
    

提交回复
热议问题