Union
The Union operation is useful when you need to merge two lists and exclude any duplicates.
It's slightly different to the Concat extension method. How? Well, the Concat method will just merge the two lists, it will not remove any duplicates.
A basic example
In the example below, we have two lists. Each containing days of the week. Notice that Thurs occurs in both lists and even duplicated in the list days2
. Using the Union
method will join these lists and remove the duplicates.
Live example: https://dotnetfiddle.net/fSduRd
var days1 = new[] {"Mon", "Tues", "Weds", "Thurs"};
var days2 = new[] {"Thurs", "Thurs", "Fri", "Sat", "Sun"};
var result = days1.Union(days2);
// output: Mon, Tues, Weds, Thurs, Fri, Sat, Sun
Union with Objects
Can we merge an array or list of objects and exclude any duplicates? Yes, yes you can.
The same Union method can be used on a list of objects as well as simple lists such as ints or strings.
As you can see below, we have two lists of people. In people2
, Jennifer, Alton, and Adam are duplicated in people1
.
N.B. We could execute the union as people2.Union(people1)
rather than people1.Union(people2)
, the outcome is the same. The only difference is the order in which they are merged.
Live example: https://dotnetfiddle.net/nCK6fA
var people1 = new[]
{
new { Id = 1112, Name = "Jennifer", City = "London"},
new { Id = 1116, Name = "Alton", City = "London"},
new { Id = 1118, Name = "Adam", City = "Paris"},
};
var people2 = new[]
{
new { Id = 1112, Name = "Jennifer", City = "London"},
new { Id = 1116, Name = "Alton", City = "London"},
new { Id = 1118, Name = "Adam", City = "Paris"},
new { Id = 1119, Name = "Milford", City = "New York"},
new { Id = 1120, Name = "James", City = "Tokyo"},
new { Id = 1121, Name = "Rachael", City = "Paris"},
};
var result = people1.Union(people2);
// output: Jennifer, Alton, Adam, Milford, James, Rachael