海军资料

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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();
        }
    }

posted on 2013-09-28 10:04  周海军  阅读(641)  评论(0编辑  收藏  举报