C#分组方式比较

网友投稿 249 2022-11-30

C#分组方式比较

测试方法:

private static void Main(string[] args) { var list = new List(); for (int i = 0; i < 1000000; i++) { list.Add(new Person() { Age = 18, Name = "老石" }); } var time1 = Time(() => { list.GroupBy(t => new { t.Age, t.Name }) .Select(t => t.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; }

public static class DistinctTest { public static void Test() { var list = new List(); for (int i = 0; i < 1000000; i++) list.Add(new Person() { Age = 18, Name = "jeffcky" }); list = list.GroupBy(t => new { t.Age, t.Name }) .Select(t => t.FirstOrDefault()) .ToList(); list = list.Distinct(d => new { d.Age, d.Name }).ToList(); list = list.Distinct((a, b) => a.Age == b.Age && a.Name == b.Name && a.count==b.count ).ToList(); } public static IEnumerable Distinct(this IEnumerable source, Func keySelector) { var hashSet = new HashSet(); foreach (TScource element in source) { if (hashSet.Add(keySelector(element))) yield return element; } } } public class Person { public string Name { get; set; } public int Age { get; set; } public int count { get; set; } }

委托:

public static class Extensions { public static IEnumerable Distinct( this IEnumerable source, Func comparer) where T : class => source.Distinct(new DynamicEqualityComparer(comparer)); public sealed class DynamicEqualityComparer : IEqualityComparer where T : class { private readonly Func _func; public DynamicEqualityComparer(Func func) { _func = func; } public bool Equals(T x, T y) => _func(x, y); public int GetHashCode(T obj) => 0; } }

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:C# 计算两个字符的相似度
下一篇:Java阻塞队列的实现及应用
相关文章

 发表评论

暂时没有评论,来抢沙发吧~