Concat() VS Union()

Asked

Viewed 395 times

9

What’s the difference between Concat() and Union() ?

When to use Concat() and when to use Union() ?

Can only be used in list ?

1 answer

11


The operator Union() returns the elements of both collections that are distinct.

Assuming 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 operator Union():

var unionResultado = primeiraLista.Union(segundaLista);

The result will be a collection containing the elements of the first and second list, without the repeated elements:

WriteLine("Union: {0}", string.Join(",", unionResultado));  // Union: 1,2,3,4,5,6

Note that normally elements are compared by reference. However, this behavior can be changed in your classes by doing override of the methods GetHashCode() and Equals().

In turn the Concat() returns the elements from the first list followed by the elements from the second list, with the 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 may 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 the namespace System.Linq and are applicable to classes implementing IEnumerable.

(See the examples given in the dotNetFiddle.)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.