ForEach.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. {
  19. throw new ArgumentNullException(nameof(source));
  20. }
  21. if (onNext == null)
  22. {
  23. throw new ArgumentNullException(nameof(onNext));
  24. }
  25. foreach (var item in source)
  26. {
  27. onNext(item);
  28. }
  29. }
  30. /// <summary>
  31. /// Enumerates the sequence and invokes the given action for each value in the sequence.
  32. /// </summary>
  33. /// <typeparam name="TSource">Source sequence element type.</typeparam>
  34. /// <param name="source">Source sequence.</param>
  35. /// <param name="onNext">Action to invoke for each element.</param>
  36. public static void ForEach<TSource>(this IEnumerable<TSource> source, Action<TSource, int> onNext)
  37. {
  38. if (source == null)
  39. {
  40. throw new ArgumentNullException(nameof(source));
  41. }
  42. if (onNext == null)
  43. {
  44. throw new ArgumentNullException(nameof(onNext));
  45. }
  46. var i = 0;
  47. foreach (var item in source)
  48. {
  49. onNext(item, checked(i++));
  50. }
  51. }
  52. }
  53. }