zoukankan      html  css  js  c++  java
  • 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; }
        }
    }
  • 相关阅读:
    spring boot 整合elasticsearch
    elasticsearch 高级查询
    elasticsearch 基本操作
    day9--回顾
    day9--多线程与多进程
    day9--paramiko模块
    day10--异步IO数据库队列缓存
    数据库连接池
    数据库事务的四大特性以及事务的隔离级别
    使用JDBC进行数据库的事务操作(2)
  • 原文地址:https://www.cnblogs.com/yxcn/p/14761158.html
Copyright © 2011-2022 走看看