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); + } + } +}