zoukankan      html  css  js  c++  java
  • List<T>.Distinct()

    class ListDistinctDemo
        {
           
    staticvoid Main(string[] args)
            {
                List
    <Person> personList =new List<Person>(){
                   
    new Person(3),//重复数据
                    new Person(3),
                   
    new Person(2),
                   
    new Person(1)
                };

               
    //使用匿名方法
                List<Person> delegateList = personList.Distinct(new Compare<Person>(
                   
    delegate(Person x, Person y)
                    {
                       
    if (null== x ||null== y) returnfalse;
                       
    return x.ID == y.ID;
                    })).ToList();

                delegateList.ForEach(s
    => Console.WriteLine(s.ID));

               
    //使用 Lambda 表达式
                List<Person> lambdaList = personList.Distinct(new Compare<Person>(
                    (x, y)
    => (null!= x &&null!= y) && (x.ID == y.ID))).ToList();

                lambdaList.ForEach(s
    => Console.WriteLine(s.ID));

               
    //排序
                personList.Sort((x, y) => x.ID.CompareTo(y.ID));
                personList.ForEach(s
    => Console.WriteLine(s.ID));

            }
        }
       
    publicclass Person
        {
           
    publicint ID { get; set; }
           
    publicstring Name { get; set; }
           
           
    public Person(int id)
            {
               
    this.ID = id;
            }
        }

       
    publicdelegatebool EqualsComparer<T>(T x, T y);

       
    publicclass Compare<T> : IEqualityComparer<T>
        {
           
    private EqualsComparer<T> _equalsComparer;

           
    public Compare(EqualsComparer<T> equalsComparer)
            {
               
    this._equalsComparer = equalsComparer;
            }

           
    publicbool Equals(T x, T y)
            {
               
    if (null!=this._equalsComparer)
                   
    returnthis._equalsComparer(x, y);
               
    else
                   
    returnfalse;
            }

           
    publicint GetHashCode(T obj)
            {
               
    return obj.ToString().GetHashCode();
            }
        }

  • 相关阅读:
    shell脚本批量启动jar
    springboot最简单的AOP
    springboot 将null字段输出为空串
    随便记录
    MySQL case when 用法
    JavaDate数据返回到前端变数字的问题
    多级菜单无限递归
    linux tomacat 之部署 war包
    linux tomcat部署 之 jre
    leetcode Best Time to Buy and Sell Stock
  • 原文地址:https://www.cnblogs.com/ziyan22/p/3343955.html
Copyright © 2011-2022 走看看