提取列表中的列表而不使其成为List<List<>>的情况有没有方法?

huangapple go评论75阅读模式
英文:

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&lt;Struct2&gt; problematicList
}

var problem = List&lt;Struct1&gt;

And I want to exctract all of Struct2's elements from a List of Struct1
Query like

List&lt;Struct2&gt; struct2s= 
                problem.Select(x =&gt; 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&lt;Struct2&gt; struct2s = problem.SelectMany(x =&gt; x.problematicList).ToList();

huangapple
  • 本文由 发表于 2023年5月21日 08:14:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76297818.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定