c# - 重构 LINQ ForEach 以返回 IEnumerable<T>

标签 c# linq plinq

我正在使用以下 CreateArray 静态方法创建一个数组:

public static int[] CreateArray(int size)
{
    var ret = new int[size];
    ret[0] = 0;
    ret[1] = 1;

    Parallel.ForEach(Enumerable.Range(2, size - 2), i =>
    {
        ret[i] = Func(i).Count();
    });

    return ret;
}

Func 的样子:

public static IEnumerable<int> Func(int i)
{
    ...
}

是否可以重构 CreateArray 方法,例如:

public static int[] CreateArray(int size)
{
    var tableFromIndex2 = ...
    return new[] { 0, 1 }
        .Concat(tableFromIndex2)
        .ToArray();
}

最佳答案

我认为 PLINQ 在这里很有用:

var tableFromIndex = ParallelEnumerable.Range(2, size - 2)
        .AsOrdered()
        .Select(i => Func(i).Count());

return new[] { 0, 1 }
        .Concat(tableFromIndex)
        .ToArray();

关于c# - 重构 LINQ ForEach 以返回 IEnumerable<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12993749/

相关文章:

c# - .NET 操作在多核机器上的非线性扩展

c# - 比较两个节点列表的总匹配度

c# - 使用 LINQ 在 Varray 中添加值

c# - C# 中的任务并行库和 PLINQ 替代方案

c# - Request.Form POSTED 变量为空

c# - 按降序排列学生

C# enctypted .accdb 连接

c# - 删除自定义 IComparable 类中的重复项

LINQ to SQL——最好的学习资源?

c# - 循环枚举器的 PLINQ 迭代导致死锁