Last active
November 19, 2019 09:35
-
-
Save EifelMono/e350245434cee29ea2258b3c1634c09a to your computer and use it in GitHub Desktop.
WithIndex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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