Search code examples
c#async-awaitaddrange

AddRange from `await` directly


I am currently returning a list of lists (List<List<string>>) from await getWorlds() and right now I am looping through each one of them, and getting the first entry in each list.

I just wonder if there is another way I can quickly add all of them directly into Worlds with .AddRange or something?

Here is my code:

var worlds = await getWorlds();
foreach (var w in worlds)
{
    Worlds.Add(w[0]);
}

Any way to shorten this to something smaller? Like Worlds = worlds.AddRange([0]); or something? I just want to get the first entry [0] and add each one to the Worlds. I'm just looking to see if there's a cleaner way of writing my code. I have not managed to find any example.


Solution

  • You can do this:

    var worlds = await getWorlds();
    Worlds.AddRange(worlds.Select(w => w[0]));
    

    Though I don't see why the foreach was so bad.