7

I need to get the return value of multiple Task<List<string>> executed in parallel and merge them into a new List<string>.

This is what I have currently. As you can see in the fiddle, the tasks are being executed in parallel (execute time is about 1s). Problem is don't know how to get the returned value (a List<string> object) from each execution so I can merge them.

Fiddle: https://dotnetfiddle.net/91YqkY

Code:

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var filters = new List<string>
        {
            "A", "B", "C"
        }

        ;
        var api = new API();
        var TaskList = new List<Task>();
        foreach (var f in filters)
        {
            var LastTask = new Task<List<String>>(() =>
            {
                return api.GetArray(f);
            }

            );
            LastTask.Start();
            TaskList.Add(LastTask);
        }

        Task.WaitAll(TaskList.ToArray());
        foreach (var t in TaskList)
        {
            // I need to get the List<string> returned in each GetArray and merge them
        }
    }
}

public class API
{
    public List<string> GetArray(string param)
    {
        Thread.Sleep(1000);
        return new List<String>{
            param + "1",
            param + "2",
            param + "3",
        };
    }
}
empz
  • 11,509
  • 16
  • 65
  • 106
  • I hate to be pedantic, but `Task`s aren't "executed in parallel" are they? They're executed asynchronously. Also, you can take action based on the completion order, or continue one based on the completion of another. – Eric Lease Jan 14 '16 at 20:07
  • You're right, but since after I start one task, the next thing I do is start the next one and so on. I allow myself to say that they are executed in parallel since total execution time is 1s and each task takes 1s to complete. – empz Jan 15 '16 at 00:47

1 Answers1

7

You could try to use the SelectMany method:

var result = TaskList.Select(t => t.Result)
                     .SelectMany(r => r)
                     .ToList();

Initially you project each element of the TaskList, which is a TaskList<string> object, to it's result which in your case is a List<string> and then using the SelectMany method you define a sequence of all the strings in the results of the tasks. Last but not least, you have to call the ToList, in order your query to be executed and to get as a result a List<string>.

Update

As Sergey correctly pointed out in his comment below, you have to redefine your TaskList.

var TaskList = new List<Task<List<string>>();
Christos
  • 53,228
  • 8
  • 76
  • 108