What is the difference between Concat()
and Union()
?
When to use Concat()
and when to use Union()
?
Can only be used in list
?
What is the difference between Concat()
and Union()
?
When to use Concat()
and when to use Union()
?
Can only be used in list
?
The Union()
operator returns the elements of both collections that are distinct.
Assuming then that we have two lists:
List<int> primeiraLista = new List<int>{1,2,3,4};
List<int> segundaLista = new List<int>{3,4,5,6};
If we apply the Union()
operator:
var unionResultado = primeiraLista.Union(segundaLista);
The result will be a collection containing the elements of the first and second list, without repeated elements :
WriteLine("Union: {0}", string.Join(",", unionResultado)); // Union: 1,2,3,4,5,6
Note that by default the elements are compared by reference. However, this behavior can be changed in your classes by overriding the GetHashCode()
and Equals()
methods.
In turn, Concat()
returns elements of the first list followed by the elements of the second list, with repeated elements included .
Assuming the two previous lists:
var concatResultado = primeiraLista.Concat(segundaLista);
WriteLine("Concat: {0}", string.Join(",", concatResultado)); // Concat: 1,2,3,4,3,4,5,6
In a final note, you can consider that Union()
= Concat().Distinct()
(although in terms of implementation and performance are different):
var concatDistinctResultado = primeiraLista.Concat(segundaLista).Distinct();
WriteLine("Concat Distinct: {0}", string.Join(",", concatDistinctResultado)); // Concat Distinct: 1,2,3,4,5,6
Both operators exist in namespace System.Linq
and are applicable to classes that implement IEnumerable
.
(See the examples given in the answer in the dotNetFiddle .)