使用Lambda/LINQ合并列表

16
如果我有类型为 IEnumerable<List<string>> 的变量,是否有可以应用于它的LINQ语句或lambda表达式,可以将这些列表组合并返回一个 IEnumerable<string>
6个回答

34

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;
      }
    }
}

虽然这有些简化了。


7

你能行吗?

myStrings.SelectMany(x => x)

2

虽然不是单个方法调用,但你应该能够编写

var concatenated = from list in lists from item in list select item;

当 'lists' 是你的 IEnumerable<List<string>>,而 concatenated 的类型是 IEnumerable<string>

(技术上来说,这实际上是对 SelectMany 方法的单个调用 - 只是它看起来并不像我在开头陈述的那样。只是想澄清一下,以防有人感到困惑或进行评论 - 我发帖后意识到自己的表述可能会让人产生误解)。


0
创建一个简单的方法。不需要使用LINQ:
IEnumerable<string> GetStrings(IEnumerable<List<string>> lists)
{
   foreach (List<string> list in lists)
   foreach (string item in list)
   {
     yield return item;
   }
 }

如果您正在使用.NET 3.5(我们可以从OP中假设),或者是在.NET 2.0和LinqBridge中使用C# 3.0,那么没有理由不使用它。 - Marc Gravell
@Marc:你说得对,特别是如果有一种容易的“linqish”方法。有时候人们只是努力地用LINQ的方式去做一些事情,让简单的事情更难以理解。 - VVS

0

使用LINQ表达式...

IEnumerable<string> myList = from a in (from b in myBigList
                                        select b)
                             select a;

...运行得很好。:-)

b将是一个IEnumerable<string>,而a将是一个string


0

这是另一个LINQ查询理解。

IEnumerable<string> myStrings =
  from a in mySource
  from b in a
  select b;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接