Lambda / LINQ中的合并列表

时间:2020-03-06 14:53:33  来源:igfitidea点击:

如果我有类型为IEnumerable &lt;List &lt;string >>的变量,是否可以使用LINQ语句或者lambda表达式,它将结合返回" IEnumerable <string>"的列表?

解决方案

选择许多即

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

尽管这有所简化。

不完全是单个方法调用,但是我们应该能够编写

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

其中" lists"是" 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;

怎么样

myStrings.SelectMany(x => x)