Distinct() with lambda?

前端 未结 18 972
南旧
南旧 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:26

    To Wrap things up . I think most of the people which came here like me want the simplest solution possible without using any libraries and with best possible performance.

    (The accepted group by method for me i think is an overkill in terms of performance. )

    Here is a simple extension method using the IEqualityComparer interface which works also for null values.

    Usage:

    var filtered = taskList.DistinctBy(t => t.TaskExternalId).ToArray();
    

    Extension Method Code

    public static class LinqExtensions
    {
        public static IEnumerable DistinctBy(this IEnumerable items, Func property)
        {
            GeneralPropertyComparer comparer = new GeneralPropertyComparer(property);
            return items.Distinct(comparer);
        }   
    }
    public class GeneralPropertyComparer : IEqualityComparer
    {
        private Func expr { get; set; }
        public GeneralPropertyComparer (Func expr)
        {
            this.expr = expr;
        }
        public bool Equals(T left, T right)
        {
            var leftProp = expr.Invoke(left);
            var rightProp = expr.Invoke(right);
            if (leftProp == null && rightProp == null)
                return true;
            else if (leftProp == null ^ rightProp == null)
                return false;
            else
                return leftProp.Equals(rightProp);
        }
        public int GetHashCode(T obj)
        {
            var prop = expr.Invoke(obj);
            return (prop==null)? 0:prop.GetHashCode();
        }
    }
    

提交回复
热议问题