Concatenation of Lists

I have 2 lists:

IndiaCities = New List (of String) from {“Banglore”, “Mumbai”}
USCities = New List (of String) from (“New York”, “Portland”)

I can concatenate both using 2 different ways:
**1. IndiaCities.Union(USCities).ToList **
2. Enumerable.Concat(IndiaCities.AsEnumerable, USCities.AsEnumerable).ToList

Both give the same output. Can you explain working of both please ?

By definition

According Enumerable.Union’s documentation, it produces the set union of two sequences: an item will only be once in the result. You can provide your equality comparer.

EDIT: in Enumerable.Concat’s documentation, a remark at the end explains the difference:

The Concat method differs from the Union method because the Concat method returns all the original elements in the input sequences. The Union method returns only unique elements.

Example

Assign List(Of String)

indiaCities = New List (of String) from {"Banglore", "Mumbai", "Shared"}
usCities = New List (of String) from {"New York", "Portland", "Shared"}

union = indiaCities.Union(usCities).ToList
concat = indiaCities.Concat(usCities).ToList

Log Message

  • String.Join(", ", union)
  • String.Join(", ", concat)

Output

  • “Banglore, Mumbai, Shared, New York, Portland”
  • “Banglore, Mumbai, Shared, New York, Portland, Shared”
6 Likes

So instead of using enumerable.cncat we can use concat() only ? Are both the same ?

Yes, I tested the code before posting: indiaCities will remains unchanged.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.