如果我有类型为
IEnumerable<List<string>>
的变量,是否有可以应用于它的LINQ语句或lambda表达式,可以将这些列表组合并返回一个 IEnumerable<string>
?SelectMany - 即
IEnumerable<List<string>> someList = ...;
IEnumerable<string> all = someList.SelectMany(x => x);
对于someList中的每个项,使用lambda "x => x"获取内部项目的IEnumerable<T>。在此情况下,每个"x"都是一个List<T>,它已经是IEnumerable<T>了。
然后将它们作为连续块返回。本质上,SelectMany类似于(简化):
static IEnumerable<TResult> SelectMany<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, IEnumerable<TResult>> selector) {
foreach(TSource item in source) {
foreach(TResult result in selector(item)) {
yield return result;
}
}
}
虽然这有些简化了。
你能行吗?
myStrings.SelectMany(x => x)
虽然不是单个方法调用,但你应该能够编写
var concatenated = from list in lists from item in list select item;
当 'lists' 是你的 IEnumerable<List<string>>
,而 concatenated 的类型是 IEnumerable<string>
。
(技术上来说,这实际上是对 SelectMany
方法的单个调用 - 只是它看起来并不像我在开头陈述的那样。只是想澄清一下,以防有人感到困惑或进行评论 - 我发帖后意识到自己的表述可能会让人产生误解)。
IEnumerable<string> GetStrings(IEnumerable<List<string>> lists)
{
foreach (List<string> list in lists)
foreach (string item in list)
{
yield return item;
}
}
使用LINQ表达式...
IEnumerable<string> myList = from a in (from b in myBigList
select b)
select a;
...运行得很好。:-)
b
将是一个IEnumerable<string>
,而a
将是一个string
。
这是另一个LINQ查询理解。
IEnumerable<string> myStrings =
from a in mySource
from b in a
select b;