简体   繁体   English

直接来自`await`的AddRange

[英]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. 我目前正在从await getWorlds()返回列表列表( List<List<string>> ),现在我正在遍历每个列表,并获取每个列表的第一个条目。

I just wonder if there is another way I can quickly add all of them directly into Worlds with .AddRange or something? 我只是想知道是否还有另一种方法可以使用.AddRange Worlds方法将所有这些方法直接快速添加到Worlds

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]); Worlds = worlds.AddRange([0]); or something? 或者其他的东西? I just want to get the first entry [0] and add each one to the Worlds . 我只想获取第一个条目[0] ,并将每个条目添加到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. 虽然我不明白为什么foreach如此糟糕。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM