英文:
Is there a way to extract list from list without making it a List<List<>> situation?
问题
从列表的列表中提取列表...
我有一个结构如下:
Struct1
{
public int blah-blah
public string blah-blah-blah
public List<Struct2> problematicList
}
var problem = List<Struct1>
我想从Struct1的列表中提取所有Struct2的元素。查询如下:
List<Struct2> struct2s =
problem.Select(x => x.problematicList.Struct2).ToList();
这给了我一个列表的列表,我无法正确理解如何使用单一的LINQ查询来完成。一定有一种方法,不是吗?
英文:
Extract list from list of lists...
I have a structure like
Struct1
{
public int blah-blah
public string blah-blah-blah
public List<Struct2> problematicList
}
var problem = List<Struct1>
And I want to exctract all of Struct2's elements from a List of Struct1
Query like
List<Struct2> struct2s=
problem.Select(x => x.problematicList.Struct2).ToList();
gives me a list of lists, and I can't wrap my head around of how to do it corretly with a singular linq query. There must be a way, is it not?
答案1
得分: 2
你寻找的是 SelectMany。
使用 SelectMany
,你可以编写类似以下的代码:
List<Struct2> struct2s = problem.SelectMany(x => x.problematicList).ToList();
英文:
What you're looking for is SelectMany.
Using SelectMany
, you would write something like the following:
List<Struct2> struct2s = problem.SelectMany(x => x.problematicList).ToList();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论