如何用LINQ从List<Struct1>提取Struct2元素避免嵌套列表?
正确提取所有Struct2元素的LINQ写法
你用Select得到嵌套列表的原因是,Select会逐个取出每个Struct1里的problematicList(本身就是List<Struct2>),最终得到List<List<Struct2>>。要把这些嵌套的集合扁平化,用SelectMany就可以实现,它会把所有子集合里的元素合并成一个单层列表。
正确的代码如下:
List<Struct2> struct2s = problem.SelectMany(x => x.problematicList).ToList();
另外注意:你原来的代码里x.problematicList.Struct2是错误写法,problematicList本身就是Struct2的集合,直接传入x.problematicList即可。
内容的提问来源于stack exchange,提问作者AvianExpress
相关产品推荐
相关产品推荐

