Distinct() with lambda?

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

    IEnumerable lambda extension:

    public static class ListExtensions
    {        
        public static IEnumerable Distinct(this IEnumerable list, Func hashCode)
        {
            Dictionary hashCodeDic = new Dictionary();
    
            list.ToList().ForEach(t => 
                {   
                    var key = hashCode(t);
                    if (!hashCodeDic.ContainsKey(key))
                        hashCodeDic.Add(key, t);
                });
    
            return hashCodeDic.Select(kvp => kvp.Value);
        }
    }
    

    Usage:

    class Employee
    {
        public string Name { get; set; }
        public int EmployeeID { get; set; }
    }
    
    //Add 5 employees to List
    List lst = new List();
    
    Employee e = new Employee { Name = "Shantanu", EmployeeID = 123456 };
    lst.Add(e);
    lst.Add(e);
    
    Employee e1 = new Employee { Name = "Adam Warren", EmployeeID = 823456 };
    lst.Add(e1);
    //Add a space in the Name
    Employee e2 = new Employee { Name = "Adam  Warren", EmployeeID = 823456 };
    lst.Add(e2);
    //Name is different case
    Employee e3 = new Employee { Name = "adam warren", EmployeeID = 823456 };
    lst.Add(e3);            
    
    //Distinct (without IEqalityComparer) - Returns 4 employees
    var lstDistinct1 = lst.Distinct();
    
    //Lambda Extension - Return 2 employees
    var lstDistinct = lst.Distinct(employee => employee.EmployeeID.GetHashCode() ^ employee.Name.ToUpper().Replace(" ", "").GetHashCode()); 
    

提交回复
热议问题