Skip to content

Instantly share code, notes, and snippets.

@EifelMono EifelMono/Program.cs
Last active Nov 19, 2019

Embed
What would you like to do?
WithIndex
using System;
using System.Collections.Generic;
using System.Linq;
namespace PlayWithIndex
{
class Program
{
static void Main()
{
var list = new List<string> { "a", "b", "c", "d" };
Console.WriteLine("foreach loop as item");
foreach (var item in list.WithIndex())
Console.WriteLine($"{item.Index} {item.Value}");
Console.WriteLine("foreach loop with tuple values");
foreach (var (value, index) in list.WithIndex())
Console.WriteLine($"{index} {value}");
Console.WriteLine("foreach method as item");
list.WithIndex().ForEach(item => Console.WriteLine($"{item.Index} {item.Value}"));
}
}
public static class LinqExtensions
{
public static IEnumerable<(T Value, int Index)> WithIndex<T>(this IEnumerable<T> source)
=> source.Select((item, index) => (item, index));
public static void ForEach<T>(this IEnumerable<T> thisValue, Action<T> action)
{
foreach (var value in thisValue)
action?.Invoke(value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.