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


    说明:

    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; }
        }
    }
  • 相关阅读:
    Python-zip压缩-解压
    使用zabbix监控nginx
    原已经安装好的nginx,现在需要添加一个未被编译安装的模块:
    zabbix 邮件告警配置
    lnmp-zabbix
    Mysql新建用户和数据库并授权
    git标签管理
    Ubuntu下安装tomcat
    git分支管理
    Java拦截器
  • 原文地址:https://www.cnblogs.com/yxcn/p/14761158.html
Copyright © 2020-2023  润新知