Distinct.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using Xunit;
  8. namespace Tests
  9. {
  10. public class Distinct : Tests
  11. {
  12. [Fact]
  13. public void Distinct_Arguments()
  14. {
  15. AssertThrows<ArgumentNullException>(() => EnumerableEx.Distinct<int, int>(null, _ => _));
  16. AssertThrows<ArgumentNullException>(() => EnumerableEx.Distinct<int, int>([1], null));
  17. AssertThrows<ArgumentNullException>(() => EnumerableEx.Distinct<int, int>(null, _ => _, EqualityComparer<int>.Default));
  18. AssertThrows<ArgumentNullException>(() => EnumerableEx.Distinct<int, int>([1], null, EqualityComparer<int>.Default));
  19. AssertThrows<ArgumentNullException>(() => EnumerableEx.Distinct<int, int>([1], _ => _, null));
  20. }
  21. [Fact]
  22. public void Distinct1()
  23. {
  24. var res = Enumerable.Range(0, 10).Distinct(x => x % 5).ToList();
  25. Assert.True(Enumerable.SequenceEqual(res, Enumerable.Range(0, 5)));
  26. }
  27. [Fact]
  28. public void Distinct2()
  29. {
  30. var res = Enumerable.Range(0, 10).Distinct(x => x % 5, new MyEqualityComparer()).ToList();
  31. Assert.True(Enumerable.SequenceEqual(res, [0, 1]));
  32. }
  33. private sealed class MyEqualityComparer : IEqualityComparer<int>
  34. {
  35. public bool Equals(int x, int y)
  36. {
  37. return x % 2 == y % 2;
  38. }
  39. public int GetHashCode(int obj)
  40. {
  41. return EqualityComparer<int>.Default.GetHashCode(obj % 2);
  42. }
  43. }
  44. }
  45. }