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

后端 未结 4 1119
一整个雨季
一整个雨季 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:04

    Jon, your solution is pretty good. One minor change though. I don't think we need EqualityComparer.Default in there. Here is my solution (ofcourse the starting point was Jon Skeet's solution)

        public static IEnumerable DistinctBy(this IEnumerable source, Func keySelector)
        {
            //TODO All arg checks
            HashSet keys = new HashSet();
            foreach (T item in source)
            {
                TKey key = keySelector(item);
                if (!keys.Contains(key))
                {
                    keys.Add(key);
                    yield return item;
                }
            }
        }
    

提交回复
热议问题