ForEach.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. namespace System.Linq
  6. {
  7. public static partial class EnumerableEx
  8. {
  9. /// <summary>
  10. /// Enumerates the sequence and invokes the given action for each value in the sequence.
  11. /// </summary>
  12. /// <typeparam name="TSource">Source sequence element type.</typeparam>
  13. /// <param name="source">Source sequence.</param>
  14. /// <param name="onNext">Action to invoke for each element.</param>
  15. public static void ForEach<TSource>(this IEnumerable<TSource> source, Action<TSource> onNext)
  16. {
  17. if (source == null)
  18. throw new ArgumentNullException(nameof(source));
  19. if (onNext == null)
  20. throw new ArgumentNullException(nameof(onNext));
  21. foreach (var item in source)
  22. onNext(item);
  23. }
  24. /// <summary>
  25. /// Enumerates the sequence and invokes the given action for each value in the sequence.
  26. /// </summary>
  27. /// <typeparam name="TSource">Source sequence element type.</typeparam>
  28. /// <param name="source">Source sequence.</param>
  29. /// <param name="onNext">Action to invoke for each element.</param>
  30. public static void ForEach<TSource>(this IEnumerable<TSource> source, Action<TSource, int> onNext)
  31. {
  32. if (source == null)
  33. throw new ArgumentNullException(nameof(source));
  34. if (onNext == null)
  35. throw new ArgumentNullException(nameof(onNext));
  36. var i = 0;
  37. foreach (var item in source)
  38. onNext(item, checked(i++));
  39. }
  40. }
  41. }