C# Distinct去重泛型List

  • List<int>去重
  • List<string>去重
  • List<T>去重

 

1、List<int>去重

1 List<int> ilist = new List<int>() { 1, 2, 3, 4, 5, 5,3,1 };
2 ilist = ilist.Distinct().ToList();
3 foreach (var item in ilist)
4 {
5 Console.WriteLine(item);
6 }

C# Distinct去重泛型List

 2、List<string>去重

 List<string> strList = new List<string>() { "4", "4", "5", "6", "6" };
 strList = strList.Distinct().ToList();
 foreach (var item in strList)
 {
    Console.WriteLine(item);
 }
C# Distinct去重泛型List

3、List<T>去重

  public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }


    //去重类
    public class LambdaComparer<T> : IEqualityComparer<T>
    {
        private readonly Func<T, T, bool> _lambdaComparer;
        private readonly Func<T, int> _lambdaHash;
        public LambdaComparer(Func<T, T, bool> lambdaComparer)
        : this(lambdaComparer, EqualityComparer<T>.Default.GetHashCode)
        {
        }
        public LambdaComparer(Func<T, T, bool> lambdaComparer, Func<T, int> lambdaHash)
        {
            if (lambdaComparer == null)
                throw new ArgumentNullException("比较值为空");
            if (lambdaHash == null)
                throw new ArgumentNullException("数组的Hash值为空");
            _lambdaComparer = lambdaComparer;
            _lambdaHash = lambdaHash;
        }
        public bool Equals(T x, T y)
        {
            return _lambdaComparer(x, y);
        }

        public int GetHashCode(T obj)
        {
            return _lambdaHash(obj);
        }
    }


 static void Main(string[] args)
        {
            List<User> list = new List<User>()
 {
    new User() { Id = 1, Name = "张三" } ,
     new User() { Id = 1, Name = "王五" } ,
    new User() { Id = 1, Name = "张三" } ,
    new User() { Id = 3, Name = "李四" } ,
 };
            list = list.Distinct(new LambdaComparer<User>((a, b) => a.Name == b.Name, obj => obj.ToString().GetHashCode())).ToList();
            foreach (var item in list)
            {
                Console.WriteLine("Id:" + item.Id + ", Name:" + item.Name);
            }
            Console.ReadLine();
        }

C# Distinct去重泛型List

 


 

 

 

上一篇:Ansible 简单使用


下一篇:Spring注解开发03--------属性赋值与自动装配