mirror of
https://github.com/jcreek/Creek.HelpfulExtensions.git
synced 2026-07-12 18:53:45 +00:00
feat(*): Add WithIndex IEnumerable extension
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
@@ -19,6 +19,8 @@
|
||||
<PackageLicenseFile>LICENSE</PackageLicenseFile>
|
||||
<RepositoryType>git</RepositoryType>
|
||||
<PackageTags>creek</PackageTags>
|
||||
<Version>1.1.0</Version>
|
||||
<AssemblyVersion>1.1.0.0</AssemblyVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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())
|
||||
{
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user