【发布时间】:2008-09-29 19:46:38
【问题描述】:
如果我有 IEnumerable<List<string>> 类型的变量,是否有一个 LINQ 语句或 lambda 表达式我可以应用到它,它将组合返回 IEnumerable<string> 的列表?
【问题讨论】:
如果我有 IEnumerable<List<string>> 类型的变量,是否有一个 LINQ 语句或 lambda 表达式我可以应用到它,它将组合返回 IEnumerable<string> 的列表?
【问题讨论】:
SelectMany - 即
IEnumerable<List<string>> someList = ...;
IEnumerable<string> all = someList.SelectMany(x => x);
对于 someList 中的每个项目,然后使用 lambda "x => x" 来获取内部项目的 IEnumerable
这些然后作为一个连续的块返回。本质上,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;
其中“列表”是您的IEnumerable<List<string>>,连接的类型是IEnumerable<string>。
(从技术上讲,这是对SelectMany 的单个方法调用 - 它看起来并不是我在开场白中的全部意思。只是想澄清一下,以防万一有人知道困惑或评论 - 在我发布它的阅读方式后我意识到)。
【讨论】:
做一个简单的方法。不需要 LINQ:
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;
【讨论】: