代码改变世界

c#使用HashSet<T>集合去重

2021-05-12 18:50  石吴玉  阅读(716)  评论(0编辑  收藏  举报

说明:

using System;
using System.Collections.Generic;
using System.Linq;

namespace JsonTest
{
    public class Program
    {
        static void Main(string[] args)
        {
            List<People> list = new List<People>();
            People temp = new People() { Name = "小明", Age = 19 };
            list.Add(new People() { Name = "小明",Age=19 });
            list.Add(new People() { Name = "小红", Age = 19 });
            list.Add(new People() { Name = "小明", Age = 19 });
            List<People> DistinctList = list.DistinctBy(x=> (x.Name,x.Age)).ToList();
            Console.Read();
        }

        public string GetName(People obj)
        {
            return obj.Name;
        }
    }
    public static class Test
    {
        /// <summary>
        /// 为集合去除重复
        /// </summary>
        /// <typeparam name="TSource">集合类型</typeparam>
        /// <typeparam name="TKey">根据xx标识去重</typeparam>
        /// <param name="source">待去重的集合</param>
        /// <param name="keySelector">去重的标识(可理解为GroupBy的key)</param>
        /// <returns></returns>
        public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
        {
            //创建一个 TKey类型的 HashSet集合
            var seenKeys = new HashSet<TKey>();
            //循环待去重的数组
            foreach (TSource element in source)
            {
                //使用 Hash集合的不能添加重复对象的特性,来判读是否重复(if能添加成功,则说明当前集合内数据未重复)
                if (seenKeys.Add(keySelector(element)))
                {
                    yield return element;
                }
            }
        }
    }

    /// <summary>
    /// 测试类
    /// </summary>
    public class People
    { 
        public string Name { get; set; }

        public int Age { get; set; }
    }
}