From 2a65026c0585b07223213a44f64fa730b642dbd7 Mon Sep 17 00:00:00 2001 From: poune05 Date: Sat, 20 Oct 2018 19:41:49 +0200 Subject: [PATCH] Add Intersect method and tests #47 --- ShittyLINQ/Intersect.cs | 32 +++++++++++++++++ ShittyLinqTests/IntersectTests.cs | 58 +++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 ShittyLINQ/Intersect.cs create mode 100644 ShittyLinqTests/IntersectTests.cs diff --git a/ShittyLINQ/Intersect.cs b/ShittyLINQ/Intersect.cs new file mode 100644 index 0000000..c4545b3 --- /dev/null +++ b/ShittyLINQ/Intersect.cs @@ -0,0 +1,32 @@ +namespace ShittyLINQ +{ + using System; + using System.Collections.Generic; + + public static partial class Extensions + { + public static IEnumerable Intersect(this IEnumerable self, IEnumerable second) + { + return Intersect(self, second, EqualityComparer.Default); + } + + public static IEnumerable Intersect(this IEnumerable self, IEnumerable second, IEqualityComparer comparer) + { + if (self == null) + throw new ArgumentNullException(nameof(self)); + if (second == null) + throw new ArgumentNullException(nameof(second)); + + foreach (var item in self) + { + foreach (var secondItem in second) + { + if (comparer.Equals(item, secondItem)) + { + yield return item; + } + } + } + } + } +} \ No newline at end of file diff --git a/ShittyLinqTests/IntersectTests.cs b/ShittyLinqTests/IntersectTests.cs new file mode 100644 index 0000000..de4cb49 --- /dev/null +++ b/ShittyLinqTests/IntersectTests.cs @@ -0,0 +1,58 @@ +namespace ShittyTests +{ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using ShittyLINQ; + using ShittyTests.TestHelpers; + + [TestClass] + public class IntersectTests + { + [TestMethod] + public void Intersect_ReturnsExpected() + { + var first = new[] { 1, 2, 3, 4, 5 }; + var second = new[] { 1, 2, 5, 6, 7 }; + var expectedResult = new[] { 1, 2, 5 }; + + var result = first.Intersect(second); + + TestHelper.AssertCollectionsAreSame(expectedResult, result); + } + + [TestMethod] + public void Intersect_ReturnsExpectedWithFirstCollectionEmpty() + { + var first = new int[] { }; + var second = new[] { 1, 2, 5, 6, 7 }; + var expectedResult = new int[] { }; + + var result = first.Intersect(second); + + TestHelper.AssertCollectionsAreSame(expectedResult, result); + } + + [TestMethod] + public void Intersect_ReturnsExpectedWithSecondCollectionEmpty() + { + var first = new[] { 1, 2, 3, 4, 5 }; + var second = new int[] { }; + var expectedResult = new int[] { }; + + var result = first.Intersect(second); + + TestHelper.AssertCollectionsAreSame(expectedResult, result); + } + + [TestMethod] + public void Intersect_ReturnsExpectedWithoutCommonValue() + { + var first = new[] { 1, 2, 3, 4, 5 }; + var second = new int[] { 6, 7, 8, 9, 10 }; + var expectedResult = new int[] { }; + + var result = first.Intersect(second); + + TestHelper.AssertCollectionsAreSame(expectedResult, result); + } + } +}