1. DistinctEqualityComparer.cs

public class DistinctEqualityComparer<T, V> : IEqualityComparer<T>
    {
        private Func<T, V> keySelector;

        public DistinctEqualityComparer(Func<T, V> keySelector)
        {
            this.keySelector = keySelector;
        }

        public bool Equals(T x, T y)
        {
            return EqualityComparer<V>.Default.Equals(keySelector(x), keySelector(y));
        }

        public int GetHashCode(T obj)
        {
            return EqualityComparer<V>.Default.GetHashCode(keySelector(obj));
        }
    }

2. DistinctExtensions.cs

public static class DistinctExtensions
    {
        public static IEnumerable<T> Distinct<T, V>(this IEnumerable<T> source, Func<T, V> keySelector)
        {
            return source.Distinct(new DistinctEqualityComparer<T, V>(keySelector));
        }
    }

3. Program.cs

class Program
    {
        static void Main(string[] args)
        {
            List<Person> personList = new List<Person>(){
                new Person(){Id = 1, Name = "Steven"},
                new Person(){Id = 2, Name = "Steven"},
                new Person(){Id = 3, Name = "Steven"},
                new Person(){Id = 3, Name = "Steven"},
            };

            List<Person> delegateList = personList.Distinct(x => x.Id).ToList();
        }
    }

相关文章:

  • 2021-12-19
  • 2022-01-28
  • 2022-12-23
  • 2022-12-23
  • 2021-10-17
  • 2021-05-19
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-02-11
  • 2022-12-23
  • 2021-12-29
  • 2021-07-02
  • 2022-01-19
  • 2022-12-23
相关资源
相似解决方案