Filippo Vitale
Filippo Vitale

Reputation: 8113

Refactor LINQ ForEach to return IEnumerable<T>

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

Upvotes: 5

Views: 981

Answers (1)

svick
svick

Reputation: 244968

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();

Upvotes: 1

Related Questions