From 783f8bba4d1d997c4625d22fdd6219578c324d89 Mon Sep 17 00:00:00 2001 From: poune05 Date: Sat, 20 Oct 2018 21:59:27 +0200 Subject: [PATCH] Add Cast extension method and tests #28 --- ShittyLINQ/Cast.cs | 24 +++++++++++++++++ ShittyLinqTests/CastTests.cs | 52 ++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 ShittyLINQ/Cast.cs create mode 100644 ShittyLinqTests/CastTests.cs diff --git a/ShittyLINQ/Cast.cs b/ShittyLINQ/Cast.cs new file mode 100644 index 0000000..2caf5c7 --- /dev/null +++ b/ShittyLINQ/Cast.cs @@ -0,0 +1,24 @@ +namespace ShittyLINQ +{ + using System; + using System.Collections; + using System.Collections.Generic; + + public static partial class Extensions + { + public static IEnumerable Cast(this IEnumerable source) + { + if (source == null) + throw new ArgumentNullException(nameof(source)); + + if (source is IEnumerable results) + { + foreach (var result in results) + yield return result; + } + + foreach (TResult result in source) + yield return result; + } + } +} \ No newline at end of file diff --git a/ShittyLinqTests/CastTests.cs b/ShittyLinqTests/CastTests.cs new file mode 100644 index 0000000..56aa3ac --- /dev/null +++ b/ShittyLinqTests/CastTests.cs @@ -0,0 +1,52 @@ +namespace ShittyTests +{ + using Microsoft.VisualStudio.TestTools.UnitTesting; + using ShittyLINQ; + using ShittyTests.TestHelpers; + using System; + using System.Collections; + using System.Collections.Generic; + + [TestClass] + public class CastTests + { + [TestMethod] + public void Cast_ReturnsExpected() + { + var source = new ArrayList { "1", "2", "3" }; + var expectedResult = new List { "1", "2", "3" }; + + + var result = source.Cast(); + + TestHelper.AssertCollectionsAreSame(expectedResult, result); + } + + [TestMethod] + public void Cast_ReturnsExpectedWithEmptyCollection() + { + var source = new ArrayList(); + var expectedResult = new List(); + + var result = source.Cast(); + + TestHelper.AssertCollectionsAreSame(expectedResult, result); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void Cast_CollectionIsNull() + { + ((ArrayList)null).Cast().ToList(); + } + + [TestMethod] + [ExpectedException(typeof(InvalidCastException))] + public void Cast_Invalid() + { + var source = new ArrayList { "1", "2", "3" }; + + source.Cast().ToList(); + } + } +} \ No newline at end of file