From 3a63fca25bfc0cf18b1b63edecfd2f5fb73613d6 Mon Sep 17 00:00:00 2001 From: Josh Creek Date: Fri, 27 Aug 2021 00:35:18 +0100 Subject: [PATCH] feat(*): Add WithIndex IEnumerable extension --- .../Creek.HelpfulExtensions.csproj | 4 ++- .../IEnumerableExtension.cs | 18 ++++++++++ README.md | 13 +++++++ UnitTests/IEnumerableExtensionTests.cs | 35 +++++++++++++++++++ 4 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 Creek.HelpfulExtensions/IEnumerableExtension.cs create mode 100644 UnitTests/IEnumerableExtensionTests.cs diff --git a/Creek.HelpfulExtensions/Creek.HelpfulExtensions.csproj b/Creek.HelpfulExtensions/Creek.HelpfulExtensions.csproj index 51c814a..d8f6643 100644 --- a/Creek.HelpfulExtensions/Creek.HelpfulExtensions.csproj +++ b/Creek.HelpfulExtensions/Creek.HelpfulExtensions.csproj @@ -1,4 +1,4 @@ - + netstandard2.0 @@ -19,6 +19,8 @@ LICENSE git creek + 1.1.0 + 1.1.0.0 diff --git a/Creek.HelpfulExtensions/IEnumerableExtension.cs b/Creek.HelpfulExtensions/IEnumerableExtension.cs new file mode 100644 index 0000000..ee24e62 --- /dev/null +++ b/Creek.HelpfulExtensions/IEnumerableExtension.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Creek.HelpfulExtensions +{ + public static class IEnumerableExtension + { + /// + /// This extension allows a foreach loop with an index + /// + public static IEnumerable<(T item, int index)> WithIndex(this IEnumerable source) + { + return source.Select((item, index) => (item, index)); + } + } +} diff --git a/README.md b/README.md index 8c1f2bc..0953f35 100644 --- a/README.md +++ b/README.md @@ -20,3 +20,16 @@ Whereas, this will result in the string `"fishmandogcat"` as the boolean passed string s = "bigfishmandogcatdoghat"; s = s.SubstringBetween("fish", "dog", true); ``` + +## IEnumerable Extensions + +### WithIndex + +This method allows you to use a foreach loop and easily access the index of each item. + +```csharp +foreach (var (item, index) in list.WithIndex()) +{ + // ... +} +``` diff --git a/UnitTests/IEnumerableExtensionTests.cs b/UnitTests/IEnumerableExtensionTests.cs new file mode 100644 index 0000000..7dd36f3 --- /dev/null +++ b/UnitTests/IEnumerableExtensionTests.cs @@ -0,0 +1,35 @@ +using NUnit.Framework; +using Creek.HelpfulExtensions; +using System.Collections.Generic; + +namespace UnitTests +{ + public class IEnumerableExtensionTests + { + [SetUp] + public void Setup() + { + } + + [Test] + public void IsSubstringBetweenFirst() + { + List list = new List() + { + 1,2,3,4,5,6,7,8,9 + }; + + string indexString = string.Empty; + string valueString = string.Empty; + + foreach (var (item, index) in list.WithIndex()) + { + indexString += index; + valueString += item; + } + + Assert.AreEqual("012345678", indexString); + Assert.AreEqual("123456789", valueString); + } + } +}