Wednesday, August 26, 2020

C# - Extension Method For ForEach

ForEach Extension for any arbitrary IEnumerable<T> sequence:

// Ex Usage
yourSequence.ForEach(x => Console.WriteLine(x)); // Extension Method public static class EnumerableExtensions { public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) { if (source == null) throw new ArgumentNullException("source"); if (action == null) throw new ArgumentNullException("action"); foreach (T item in source) { action(item); } } }

If you're dealing with an array then you can use the built-in static ForEach method:

Array.ForEach(yourArray, x => Console.WriteLine(x));

If you're dealing with a List<T> then you can use the built-in ForEach instance method:

yourList.ForEach(x => Console.WriteLine(x));

No comments:

Post a Comment