Saadi
Saadi

Reputation: 2237

How to return List from Task.WhenAll instead of array

I'm trying to find a solution to this but but haven't been able to find one. That's why I'm asking here.

I have a list of tasks with two items

List<Task<int>> tasks = new List<Task<int>>();
tasks.Add(Task.FromResult(1));
tasks.Add(Task.FromResult(2));

When I call await Task.WhenAll(tasks), it returns int[] but I want it to return List<int>. Like below:

List<int> result = await Task.WhenAll(tasks);

I want to be able to add new items to the list after it's created.

Upvotes: 8

Views: 12484

Answers (1)

Peter
Peter

Reputation: 27944

You can write:

List<int> result = (await Task.WhenAll(tasks)).ToList();

This will convert the array to a list.

Do not forget to add the namespace:

using System.Linq;

Upvotes: 32

Related Questions