DistinctTest.cs 1.8 KB

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