结合Lambda/LINQ中的列表

16 .net c# linq lambda

如果我有类型的变量IEnumerable<List<string>>是有一个LINQ语句或lambda表达式我可以应用于它将组合返回一个IEnumerable<string>

Mar*_*ell 33

SelectMany - 即

        IEnumerable<List<string>> someList = ...;
        IEnumerable<string> all = someList.SelectMany(x => x);
Run Code Online (Sandbox Code Playgroud)

对于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;
      }
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然这有所简化.


Jar*_*Par 7

怎么样

myStrings.SelectMany(x => x)
Run Code Online (Sandbox Code Playgroud)