开发者

How to append enumerable collection to an existing list in C#

i have three functions which are returning an IEnumerable collection. now i want to combine all these into one List. so, is there any m开发者_JS百科ethod by which i can append items from IEnumerable to a list. i mean without for each loop?


Well, something will have to loop... but in LINQ you could easily use the Concat and ToList extension methods:

var bigList = list1.Concat(list2).Concat(list3).ToList();

Note that this will create a new list rather than appending items to an existing list. If you want to add them to an existing list, List<T>.AddRange is probably what you're after:

bigList.AddRange(list1);
bigList.AddRange(list2);
bigList.AddRange(list3);


If you already have a list:

list.AddRange(yourCollectionToAppend);

If you have 2 enumerables and haven't created the list yet:

firstCollection.Concat(secondCollection).ToList();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜