How to merge a collection of collections in Linq

后端 未结 2 1382
野的像风
野的像风 2021-02-05 00:03

I would like to be able to fusion an IEnumerable> into IEnumerable (i.e. merge all individual collections into one)

相关标签:
2条回答
  • 2021-02-05 00:13
    var lists = GetTheNestedCase();
    return
        from list in lists
        from element in list
        select element;
    

    is another way of doing this using C# 3.0 query expression syntax.

    0 讨论(0)
  • 2021-02-05 00:31

    Try

    var it = GetTheNestedCase();
    return it.SelectMany(x => x);
    

    SelectMany is a LINQ transformation which essentially says "For Each Item in a collection return the elements of a collection". It will turn one element into many (hence SelectMany). It's great for breaking down collections of collections into a flat list.

    0 讨论(0)
提交回复
热议问题