How to merge a collection of collections in Linq

久未见 提交于 2019-12-03 10:26:27

问题


I would like to be able to fusion an IEnumerable<IEnumerable<T>> into IEnumerable<T> (i.e. merge all individual collections into one). The Union operators only applies to two collections. Any idea?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/321229/how-to-merge-a-collection-of-collections-in-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!