feat(*): Add WithIndex IEnumerable extension

This commit is contained in:
Josh Creek
2021-08-27 00:35:18 +01:00
parent 06c6057876
commit 3a63fca25b
4 changed files with 69 additions and 1 deletions
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework> <TargetFramework>netstandard2.0</TargetFramework>
@@ -19,6 +19,8 @@
<PackageLicenseFile>LICENSE</PackageLicenseFile> <PackageLicenseFile>LICENSE</PackageLicenseFile>
<RepositoryType>git</RepositoryType> <RepositoryType>git</RepositoryType>
<PackageTags>creek</PackageTags> <PackageTags>creek</PackageTags>
<Version>1.1.0</Version>
<AssemblyVersion>1.1.0.0</AssemblyVersion>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Creek.HelpfulExtensions
{
public static class IEnumerableExtension
{
/// <summary>
/// This extension allows a foreach loop with an index
/// </summary>
public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> source)
{
return source.Select((item, index) => (item, index));
}
}
}
+13
View File
@@ -20,3 +20,16 @@ Whereas, this will result in the string `"fishmandogcat"` as the boolean passed
string s = "bigfishmandogcatdoghat"; string s = "bigfishmandogcatdoghat";
s = s.SubstringBetween("fish", "dog", true); 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())
{
// ...
}
```
+35
View File
@@ -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<int> list = new List<int>()
{
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);
}
}
}