Skip to content

Instantly share code, notes, and snippets.

@EifelMono
Last active November 19, 2019 09:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EifelMono/e350245434cee29ea2258b3c1634c09a to your computer and use it in GitHub Desktop.
Save EifelMono/e350245434cee29ea2258b3c1634c09a to your computer and use it in GitHub Desktop.
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