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.
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.
This is not quite what you're looking for, but you could do this to add all instances of items in all the sub-lists too, rather than just the first one.. (this will flatten the list into a single list of items)
var worlds = await getWorlds();
Worlds.AddRange(worlds.SelectMany(w=>w));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.