C#LINQ对对象进行去重

首先实现一个扩展方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FirstProject
{
    ///


    /// LINQ 扩展方法类
    ///

    public static class LINQExtention
    {
        public static IEnumerable DistinctByFields(this IEnumerable source, Func selector)
        {
            // 通过HashSet的特性(值不重复)来去重
            HashSet keySet = new HashSet();
            List list = new List();

            foreach (var item in source)
            {
                if (keySet.Add(selector(item)))
                {
                    // 如果能成功添加到HashSet中,表明不是重复的数据
                    list.Add(item);
                }
            }
            return list;
        }
    }
}

其次是调用

            // 创建学生集合
            List stuList = new List()
            {
                new Student { ID = "1",Name = "张三",Age = 18},
                new Student { ID = "2",Name = "李四",Age = 18},
                new Student { ID = "3",Name = "王五",Age = 18},
                new Student { ID = "4",Name = "赵六",Age = 20},
                new Student { ID = "5",Name = "田七",Age = 21},
                new Student { ID = "6",Name = "张三",Age = 21}
            };

            // 单字段去重
             var stus = stuList.DistinctByFields(p => p.Name);

            // 多字段去重
            // var stus = stuList.DistinctByFields(p => new { p.Name, p.Age });

            foreach (var item in stus)
            {
                Console.WriteLine("学生ID:{0},学生姓名:{1},学生年龄:{2}", item.ID, item.Name, item.Age);
            }


你可能感兴趣的:(LINQ去重,c#)