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

Samuel Rossille picture Samuel Rossille · Jan 4, 2013 · Viewed 118.2k times · Source

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 build-in method in .Net to do that or do I have to write it myself?

Answer

Jon Skeet picture Jon Skeet · Jan 4, 2013

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