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

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接口。

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值