Skip to content

Commit

Permalink
Función de enumeración con índice
Browse files Browse the repository at this point in the history
  • Loading branch information
TheXDS committed Nov 18, 2023
1 parent beaba10 commit 464bff2
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/Lib/MCART/Helpers/CollectionHelpers.cs
Expand Up @@ -633,6 +633,24 @@ public static IEnumerable<double> ToPercentDouble(this IEnumerable<int> collecti
return ToPercentDouble(collection, 0, max);
}

/// <summary>
/// Enumera los elementos de la colección, incluyendo el índice de cada
/// elemento devuelto.
/// </summary>
/// <typeparam name="T">Tipo de elementos de la colección.</typeparam>
/// <param name="collection">
/// Colección para la cual enumerar los elementos junto con su índice.
/// </param>
/// <returns>Una enumeración de cada elemento junto a su índice.</returns>
public static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> collection)
{
int i = 0;
foreach (var j in collection)
{
yield return (i++, j);
}
}

/// <summary>
/// Convierte los valores de una colección de elementos
/// <see cref="int" /> a porcentajes.
Expand Down
6 changes: 6 additions & 0 deletions src/Tests/Lib/MCART.Tests/Helpers/CollectionHelpersTests.cs
Expand Up @@ -406,6 +406,12 @@ public async Task ToPercentAsync_Test_Double()
Assert.AreEqual(new[] { 0.2, 0.4, 0.6, 0.8, 1.0, double.NaN }, await Read(GetValuesAsync<double>(double.NaN).ToPercent(0, 5)));
}

[Test]
public void WithIndex_test()
{
Assert.That("ABC".ToCharArray().WithIndex(), Is.EquivalentTo(new (int, char)[] { (0,'A'), (1, 'B'), (2, 'C') }));
}

private static async IAsyncEnumerable<T> GetValuesAsync<T>(T? tail = null) where T : struct
{
yield return (T)Convert.ChangeType(1, typeof(T));
Expand Down

0 comments on commit 464bff2

Please sign in to comment.