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?
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");
Unfortunately, List<T>. AddRange isn't defined in any interface.
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!
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With