暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

C# Linq 的三种去重方式(Distinct)

Net分享 2021-09-01
5617

前言

首先给出我们需要用到的对象,如下:

public class Person
{
    public string Name { getset; }
    public int Age { getset; }
}

接下来我们添加100万条数据到集合中,如下:

            var list = new List<Person>();
            for (int i = 0; i < 1000000; i++)
            {
                list.Add(new Person() { Age = 18, Name = "迷恋自留地" });
            }
            for (int i = 0; i < 1000; i++)
            {
                list.Add(new Person() { Age = 19, Name = "迷恋自留地" });
            }

第一种分组去重

年龄和名称进行分组,然后取第一条即可达到去重,如下:

var  list1 = list.GroupBy(d => new { d.Age, d.Name })
    .Select(d => d.FirstOrDefault())
    .ToList();

第二种 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  list2 = list.Distinct(d => new { d.Age, d.Name }).ToList();

第三种 IEqualityComparer去重 (扩展方法)


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();

性能比较

我们来分析其耗时情况,如下:

var list = new List<Person>();
for (int i = 0; i < 1000000; i++)
{
    list.Add(new Person() { Age = 18, Name = "jeffcky" });
}

var time1 = Time(() =>
{
    list.GroupBy(d => new { d.Age, d.Name })
        .Select(d => d.FirstOrDefault())
        .ToList();
});
Console.WriteLine($"分组耗时:{time1}");

var time2 = Time(() =>
{
    list.Distinct(d => new { d.Age, d.Name }).ToList();
});
Console.WriteLine($"HashSet耗时:{time2}");

var time3 = Time(() =>
{
    list.Distinct((a, b) => a.Age == b.Age && a.Name == b.Name).ToList();
});
Console.WriteLine($"委托耗时:{time3}");


static long Time(Action action)
{
    var stopwatch = new Stopwatch();
    stopwatch.Start();
    action();
    stopwatch.Stop();
    return stopwatch.ElapsedMilliseconds;
}



  1. 五分钟完全弄懂C#特性

  2. redis中的 缓存穿透、缓存击穿、缓存雪崩区别和解决方案

  3. 为什么要用队列消息(mq)?

  4. C# 使用RabbitMQ的完整图解

  5. VS中进行编码时智能提示由英文切换为中文

  6. 开源项目-一沙后台管理(core-mvc-缓存,支持多数据库)

  7. ASP.NET Core中使用NLog记录日志

  8. Visual Studio中Git的使用

  9. [完全图解]NET Croe 使用JWT验证签名




参考:https://www.cnblogs.com/CreateMyself/p/12863407.html


文章转载自Net分享,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论