C# Linq:列表列表到长列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/649773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Linq: List of lists to a long list
提问by Chau
I've got an object of type A
which consists of a list of objects of type B
:
我有一个类型的对象,A
它由类型的对象列表组成B
:
class A { list<B> Alist;}
class B { string C; string D;}
In my program I have a list of A
objects:
在我的程序中,我有一个A
对象列表:
list<A> listOfA = computeAList();
and I would like to select all the C
strings in that list. The following statement I hoped would give me the result I wanted; it returns a list of lists containing the C
's:
我想选择C
该列表中的所有字符串。我希望下面的语句能给我想要的结果;它返回一个包含C
's的列表列表:
var query = from objectA in listOfA
select objectA.Alist.FindAll(x => x.C.Length > 0).C;
Is there a way to get a single list of all the C
's instead?
有没有办法获得所有C
's的单个列表?
采纳答案by Jon Skeet
ybo's answer would have been my first response too. The query expression equivalent of this is:
ybo 的回答也是我的第一反应。与此等效的查询表达式是:
var query = from a in computeAList()
from b in a.Alist
select b.C;
For the sake of completeness, the other answers in this thread are variations on the same theme.
为了完整起见,该线程中的其他答案是同一主题的变体。
From ybo (the exact same query, expressed as dot notation):
来自 ybo(完全相同的查询,表示为点符号):
var query = listOfA.SelectMany(a => a.Alist, (a, b) => b.C);
From Ray Hayes (including the Where clause; I've reformatted slightly):
来自 Ray Hayes(包括 Where 子句;我稍微重新格式化了):
var query = listOfA.SelectMany(a => a.AList, (a, b) => b.C)
.Where(c => c.Length > 0);
回答by Ray Hayes
I too would have had a similar answer, my only modification was to add the where clause to avoid having empty strings (where C is empty):
我也会有类似的答案,我唯一的修改是添加 where 子句以避免出现空字符串(其中 C 为空):
listOfA.SelectMany( a => a.AList, (a, b) => b.C ).Where( c => c.Length > 0 );