Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactor LINQ ForEach to return IEnumerable<T>

Tags:

c#

linq

plinq

I am creating an array with the following CreateArray static method:

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;
}

Where Func looks like:

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

Is it possible to refactor the CreateArray method in something like:

public static int[] CreateArray(int size)
{
    var tableFromIndex2 = ...
    return new[] { 0, 1 }
        .Concat(tableFromIndex2)
        .ToArray();
}
like image 425
Filippo Vitale Avatar asked Nov 12 '22 19:11

Filippo Vitale


1 Answers

I think PLINQ could be useful here:

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

return new[] { 0, 1 }
        .Concat(tableFromIndex)
        .ToArray();
like image 88
svick Avatar answered Nov 15 '22 10:11

svick