測試方法:
private static void Main(string[] args) { var list = new List<Person>(); 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<Person>(); 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<TScource> Distinct<TScource, TKey>(this IEnumerable<TScource> source, Func<TScource, TKey> keySelector) { var hashSet = new HashSet<TKey>(); 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<T> Distinct<T>( this IEnumerable<T> source, Func<T, T, bool> comparer) where T : class => source.Distinct(new DynamicEqualityComparer<T>(comparer)); public 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; } }