ForEach.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Threading.Tasks;
  8. namespace System.Linq
  9. {
  10. public static partial class EnumerableEx
  11. {
  12. /// <summary>
  13. /// Enumerates the sequence and invokes the given action for each value in the sequence.
  14. /// </summary>
  15. /// <typeparam name="TSource">Source sequence element type.</typeparam>
  16. /// <param name="source">Source sequence.</param>
  17. /// <param name="onNext">Action to invoke for each element.</param>
  18. public static void ForEach<TSource>(this IEnumerable<TSource> source, Action<TSource> onNext)
  19. {
  20. if (source == null)
  21. throw new ArgumentNullException(nameof(source));
  22. if (onNext == null)
  23. throw new ArgumentNullException(nameof(onNext));
  24. foreach (var item in source)
  25. onNext(item);
  26. }
  27. /// <summary>
  28. /// Enumerates the sequence and invokes the given action for each value in the sequence.
  29. /// </summary>
  30. /// <typeparam name="TSource">Source sequence element type.</typeparam>
  31. /// <param name="source">Source sequence.</param>
  32. /// <param name="onNext">Action to invoke for each element.</param>
  33. public static void ForEach<TSource>(this IEnumerable<TSource> source, Action<TSource, int> onNext)
  34. {
  35. if (source == null)
  36. throw new ArgumentNullException(nameof(source));
  37. if (onNext == null)
  38. throw new ArgumentNullException(nameof(onNext));
  39. var i = 0;
  40. foreach (var item in source)
  41. onNext(item, checked(i++));
  42. }
  43. }
  44. }