Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 method by which i can append items from IEnumerable to a list. i mean without for each loop?

like image 240
Radhi Avatar asked Nov 01 '10 07:11

Radhi


People also ask

How do I add items to an IEnumerable list?

What you can do is use the Add extension method to create a new IEnumerable<T> with the added value. var items = new string[]{"foo"}; var temp = items; items = items. Add("bar");

Is it possible to use Add or AddRange methods on IEnumerable?

Unfortunately, List<T>. AddRange isn't defined in any interface.

How do I empty my IEnumerable?

Clear() will empty out an existing IEnumerable. model. Categories = new IEnumerable<whatever>() will create a new empty one. It may not be a nullable type - that would explain why it can't be set to null.

What is IEnumerable C#?

IEnumerable in C# is an interface that defines one method, GetEnumerator which returns an IEnumerator interface. This allows readonly access to a collection then a collection that implements IEnumerable can be used with a for-each statement.


1 Answers

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); 
like image 95
Jon Skeet Avatar answered Sep 17 '22 16:09

Jon Skeet