ForEach.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT 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. {
  23. onNext(item);
  24. }
  25. }
  26. /// <summary>
  27. /// Enumerates the sequence and invokes the given action for each value in the sequence.
  28. /// </summary>
  29. /// <typeparam name="TSource">Source sequence element type.</typeparam>
  30. /// <param name="source">Source sequence.</param>
  31. /// <param name="onNext">Action to invoke for each element.</param>
  32. public static void ForEach<TSource>(this IEnumerable<TSource> source, Action<TSource, int> onNext)
  33. {
  34. if (source == null)
  35. throw new ArgumentNullException(nameof(source));
  36. if (onNext == null)
  37. throw new ArgumentNullException(nameof(onNext));
  38. var i = 0;
  39. foreach (var item in source)
  40. {
  41. onNext(item, checked(i++));
  42. }
  43. }
  44. }
  45. }