Coder Perfect

How can I make a new IEnumerableT> by concatenating two IEnumerableT>?


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

Is there a built-in function for this in.NET, or will I have to develop it myself?

Asked by Samuel Rossille

Solution #1

Yes, Enumerable is supported by LINQ to Objects. Concat:

var together = first.Concat(second);

NB: If either first or second is null, an ArgumentNullException will be thrown. Use the null coalescing operator like this to avoid this and treat nulls like an empty set:

var together = (first ?? Enumerable.Empty<string>()).Concat(second ?? Enumerable.Empty<string>()); //amending `<string>` to the appropriate type

Answered by Jon Skeet

Solution #2

The Concat method returns an object that implements IEnumerableT> by returning an object (named Cat) whose enumerator attempts to use the two passed-in enumerable elements (named A and B) in order. Cat can be used directly if the passed-in enumerables reflect sequences that will not change throughout Cat’s lifespan and can be read from without causing side effects. Otherwise, doing ToList() on Cat and using the resulting ListT> could be a smart idea (which will represent a snapshot of the contents of A and B).

When enumeration begins, certain enumerables take a snapshot of the collection and return data from that snapshot if the collection is modified during the enumeration. If B is an enumerable, any change to B that occurs before Cat reaches the end of A will be reflected in Cat’s enumeration, but changes that occur after that will not. Such semantics are likely to be perplexing; nevertheless, by snapping a picture of Cat, you can sidestep these problems.

Answered by supercat

Solution #3

For your solution, use the following code: –

public void Linq94() 
    int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; 
    int[] numbersB = { 1, 3, 5, 7, 8 }; 

    var allNumbers = numbersA.Concat(numbersB); 

    Console.WriteLine("All numbers from both arrays:"); 
    foreach (var n in allNumbers) 

Answered by Jay Shukla

Solution #4

I realise this is an old post, but if you want to concatenate many IEnumerables, I recommend using the following code.

var joinedSel = new[] { first, second, third }.Where(x => x != null).SelectMany(x => x);

This prevents null IEnumerables from being created and allows for numerous concatenations.

Answered by craig1231

Solution #5

// The answer that I was looking for when searching
public void Answer()
    IEnumerable<YourClass> first = this.GetFirstIEnumerableList();
    // Assign to empty list so we can use later
    IEnumerable<YourClass> second = new List<YourClass>();

    if (IwantToUseSecondList)
        second = this.GetSecondIEnumerableList();  
    IEnumerable<SchemapassgruppData> concatedList = first.Concat(second);

Answered by Hasse

Post is based on