Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate two IEnumerable<T> into a new IEnumerable<T>?

I have two instances of IEnumerable<T> (with the same T). I want a new instance of IEnumerable<T> which is the concatenation of both.

Is there a built-in method in .NET to do that or do I have to write it myself?

like image 993
Samuel Rossille Avatar asked Jan 04 '13 21:01

Samuel Rossille


People also ask

How do I append to IEnumerable?

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.

Can you use Linq on IEnumerable?

All LINQ methods are extension methods to the IEnumerable<T> interface. That means that you can call any LINQ method on any object that implements IEnumerable<T> . You can even create your own classes that implement IEnumerable<T> , and those classes will instantly "inherit" all LINQ functionality!

What is the return type of IEnumerable in C#?

IEnumerable has just one method called GetEnumerator. This method returns another type which is an interface that interface is IEnumerator. If we want to implement enumerator logic in any collection class, it needs to implement IEnumerable interface (either generic or non-generic).


1 Answers

Yes, LINQ to Objects supports this with Enumerable.Concat:

var together = first.Concat(second); 

NB: Should first or second be null you would receive a ArgumentNullException. To avoid this & treat nulls as you would an empty set, use the null coalescing operator like so:

var together = (first ?? Enumerable.Empty<string>()).Concat(second ?? Enumerable.Empty<string>()); //amending `<string>` to the appropriate type 
like image 189
Jon Skeet Avatar answered Sep 24 '22 11:09

Jon Skeet