Remove duplicates from a List in C#

前端 未结 27 1836
广开言路
广开言路 2020-11-22 04:41

Anyone have a quick method for de-duplicating a generic List in C#?

27条回答
  •  鱼传尺愫
    2020-11-22 05:16

    If you have tow classes Product and Customer and we want to remove duplicate items from their list

    public class Product
    {
        public int Id { get; set; }
        public string ProductName { get; set; }
    }
    
    public class Customer
    {
        public int Id { get; set; }
        public string CustomerName { get; set; }
    
    }
    

    You must define a generic class in the form below

    public class ItemEqualityComparer : IEqualityComparer where T : class
    {
        private readonly PropertyInfo _propertyInfo;
    
        public ItemEqualityComparer(string keyItem)
        {
            _propertyInfo = typeof(T).GetProperty(keyItem, BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);
        }
    
        public bool Equals(T x, T y)
        {
            var xValue = _propertyInfo?.GetValue(x, null);
            var yValue = _propertyInfo?.GetValue(y, null);
            return xValue != null && yValue != null && xValue.Equals(yValue);
        }
    
        public int GetHashCode(T obj)
        {
            var propertyValue = _propertyInfo.GetValue(obj, null);
            return propertyValue == null ? 0 : propertyValue.GetHashCode();
        }
    }
    

    then, You can remove duplicate items in your list.

    var products = new List
                {
                    new Product{ProductName = "product 1" ,Id = 1,},
                    new Product{ProductName = "product 2" ,Id = 2,},
                    new Product{ProductName = "product 2" ,Id = 4,},
                    new Product{ProductName = "product 2" ,Id = 4,},
                };
    var productList = products.Distinct(new ItemEqualityComparer(nameof(Product.Id))).ToList();
    
    var customers = new List
                {
                    new Customer{CustomerName = "Customer 1" ,Id = 5,},
                    new Customer{CustomerName = "Customer 2" ,Id = 5,},
                    new Customer{CustomerName = "Customer 2" ,Id = 5,},
                    new Customer{CustomerName = "Customer 2" ,Id = 5,},
                };
    var customerList = customers.Distinct(new ItemEqualityComparer(nameof(Customer.Id))).ToList();
    

    this code remove duplicate items by Id if you want remove duplicate items by other property, you can change nameof(YourClass.DuplicateProperty) same nameof(Customer.CustomerName) then remove duplicate items by CustomerName Property.

提交回复
热议问题