c#中List的元素遍历(foreach)和去重复(distinct)

来源:互联网 发布:青少年普法网络大赛 编辑:程序博客网 时间:2024/05/22 02:05

c#中List的元素遍历(foreach)和去重复(distinct)

一、准备工作

定义实体类people

    public List<People> PeopleList { get; set; }    public class People    {        public string Name { get; set; }        public int Age { get; set; }    }

实体比较help类

    public delegate bool CompareDelegate<T>(T x, T y);    public class ListCompare<T> : IEqualityComparer<T>    {        private CompareDelegate<T> _compare;        public ListCompare(CompareDelegate<T> d)        {            this._compare = d;        }        public bool Equals(T x, T y)        {            if (_compare != null)            {                return this._compare(x, y);            }            else            {                return false;            }        }        public int GetHashCode(T obj)        {            return obj.ToString().GetHashCode();        }    }

二、List.ForEach()

假设需要对集合中的每个元素进行运算(将每个人的年龄增加10岁)

    PeopleList.ForEach(p=>{        p.Age = p.Age + 10;    });

三、List.Distinct()

假设需要将姓名和年龄相同的元素过滤掉

    PeopleList.Distinct(new Common.List.ListCompare<People>(        (x,y)=> x.Name==y.Name&&x.Age==y.Age)        );

解析:

ListCompare类用来比较List中的两个元素。它的构造函数中需要传入一个CompareDelegate。
可以看出,两个元素的比较,重点在CompareDelegate中。
定义: public delegate bool CompareDelegate(T x, T y);
其实,ListCompare实现了IEqualityComparer接口。

原创粉丝点击