LINQ的:名单列出一个长长的清单
我有类型的对象 A
它由键入 B
的对象的列表:
I've got an object of type A
which consists of a list of objects of type B
:
class A { list<B> Alist;}
class B { string C; string D;}
在我的节目,我有的名单code>对象:
In my program I have a list of A
objects:
list<A> listOfA = computeAList();
和我想选择所有的 C
在该列表中的字符串。下面的语句我希望能给我我想要的结果;它返回一个包含 C
的名单列表:
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:
var query = from objectA in listOfA
select objectA.Alist.FindAll(x => x.C.Length > 0).C;
有没有办法让所有的 C 单列表code>的呢?
YBO的回答将是我太第一反应。查询表达式相当于是这样的:
ybo's answer would have been my first response too. The query expression equivalent of this is:
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.
从YBO(完全相同的查询,表示为点表示):
From ybo (the exact same query, expressed as dot notation):
var query = listOfA.SelectMany(a => a.Alist, (a, b) => b.C);
从雷·海斯(包括Where子句,我已经稍微重新格式化):
From Ray Hayes (including the Where clause; I've reformatted slightly):
var query = listOfA.SelectMany(a => a.AList, (a, b) => b.C)
.Where(c => c.Length > 0);