Viyi.Util/Linq/EnumerableExtensions.ForEach.cs

(完整代码) 2KB

namespace Viyi.Util.Linq;

public static partial class EnumerableExtensions {
    /// <summary>
    /// 等同于无参数的 ForEach(),目的是为了执行 Enumerable 的遍历
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="source"></param>
    public static void Enumerate<T>(this IEnumerable<T> source) {
        foreach (var it in source) { }
    }

    /// <summary>
    /// Enumerate 的别名,目的是为了执行 Enumerable 的遍历
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="source"></param>
    public static void ForEach<T>(this IEnumerable<T> source) => Enumerate(source);

    public static void ForEach<T>(this IEnumerable<T> source, Action<T> process) {
        foreach (var it in source) { process(it); }
    }

    public static void ForEach<T>(this IEnumerable<T> source, Action<T, int> process) {
        foreach (var (it, index) in source.Select((it, index) => (it, index))) {
            process(it, index);
        }
    }

    public static void ForEach<T, R>(this IEnumerable<T> source, Func<T, R> process) {
        foreach (var it in source) { process(it); }
    }

    public static void ForEach<T, R>(this IEnumerable<T> source, Func<T, int, R> process) {
        source.Select(process).Enumerate();
    }

    public static async Task ForEachAsync<T>(this IEnumerable<T> source, Func<T, Task> process) {
        foreach (var it in source) { await process(it); }
    }

    public static async Task ForEachAsync<T>(this IEnumerable<T> source, Func<T, int, Task> process) {
        foreach (var (it, index) in source.Select((it, index) => (it, index))) {
            await process(it, index);
        }
    }

    public static async Task ForEachAsync<T, R>(this IEnumerable<T> source, Func<T, Task<R>> process) {
        foreach (var it in source) { await process(it); }
    }

    public static async Task ForEachAsync<T, R>(this IEnumerable<T> source, Func<T, int, Task<R>> process) {
        foreach (var (it, index) in source.Select((it, index) => (it, index))) {
            await process(it, index);
        }
    }
}

24 小时内免费解锁 3 个项目,之后 1 积分/个。 规则说明

AI 解读

登录后可用,每次 10 积分,解读结果公开显示在下面。

还没有人解读过这个文件。