Linq 的三种去重方式(Distinct)及 操作字典 Dictionary

//关于C#中默认的Distinct方法在什么情况下才能去重,这个就不用我再多讲,针对集合对象去重默认实现将不再满足,于是乎我们需要自定义实现来解决这个问题,接下来我们详细讲解几种常见去重方案。
//
定义一个对象 public class User { public int Age{ get; set; } public string Name { get; set; } } //添加数据到集合中,如下: var list = new List<User>(); for (int i = 0; i < 10000; i++) { list.Add(new User() { Age = 26, Name = "张三" }); } for (int i = 0; i < 1000; i++) { list.Add(new User() { Age = 28, Name = "李四" }); } //第一种分组去重 年龄和姓名进行分组,然后取第一条即可达到去重,如下: var list1 = list.GroupBy(a => new { a.Age, a.Name }) .Select(a => a.FirstOrDefault()) .ToList(); 第二种 HashSet去重 (扩展方法) C#中HashSet对于重复元素会进行过滤筛选,所以我们写下如下扩展方法(在静态函数中定义),遍历集合元素,最后利用HashSet进行过滤达到去重目的,如下: public static IEnumerable<TSource> Distinct<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { var hashSet = new HashSet<TKey>(); foreach (TSource element in source) { if (hashSet.Add(keySelector(element))) { yield return element; } } } 述扩展方法即可去重,如下: var list = list.Distinct(a => new { a.Age, a.Name }).ToList(); 第三种 IEqualityComparer去重 (扩展方法) 在实际项目中有很多通过具体实现类实现该接口,通过重写Equals和HashCode比较属性值来达到去重目的,因为对于每一个类都得实现对应比较器,所以并不通用,反而利用上述方式才是最佳,
其实我们大可借助该比较接口实现通用解决方案,对于每一个类都得实现一个比较器的原因在于,我们将属性比较放在类该接口内部,如果我们将属性比较放在外围呢,这个时候就达到了通用解决方案,
那么我们怎么实现呢,
通过委托来实现,实现该接口的本质无非就是比较HashCode,然后通过Equals比较其值,当比较HashCode时,我们强制其值为一个常量(比如0),当重写Equals方法我们调用委托即可,如下
public static class Extensions { public static IEnumerable<T> Distinct<T>( this IEnumerable<T> source, Func<T, T, bool> comparer) where T : class => source.Distinct(new DynamicEqualityComparer<T>(comparer)); private sealed class DynamicEqualityComparer<T> : IEqualityComparer<T> where T : class { private readonly Func<T, T, bool> _func; public DynamicEqualityComparer(Func<T, T, bool> func) { _func = func; } public bool Equals(T x, T y) => _func(x, y); public int GetHashCode(T obj) => 0; } } 通过指定属性进行比较即可去重,如下: list = list.Distinct((a, b) => a.Age == b.Age && a.Name == b.Name).ToList(); 参考:https://www.cnblogs.com/CreateMyself/p/12863407.html

 

//Linq 操作字典Dictionary
 Dictionary<int, User> dicValue = new Dictionary<int, User>()
            {
                {4,new User{Age=60,Name = "钱四"} }
            };
            dicValue.Add(1, new User() { Age = 20, Name= "张三"});
            dicValue.Add(2, new User() { Age = 30, Check = "李二"});
            dicValue.Add(3, new User() { Age = 40, Check = "王五" });

            var dic = dicValue.Where(x => x.Value.Age == 30).Select(z => new { key = z.Key, value = z.Value }).ToDictionary(x => x.key, x => x.value);

            foreach (KeyValuePair<int,User> item in dic)
            {
                Console.WriteLine(item.Key.ToString());
            }

 

posted @ 2022-03-14 16:36  ₯㎕~  阅读(1679)  评论(0编辑  收藏  举报