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

梦想与她 提交于 2019-12-20 10:25:33

问题


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


回答1:


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



回答2:


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();


来源:https://stackoverflow.com/questions/4067223/how-to-append-enumerable-collection-to-an-existing-list-in-c-sharp

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