Thursday, June 14, 2012

Concat() vs Union()

Shout it kick it on DotNetKicks.com
Recently I worked with the two method on my enumeration object that are Union() and Concat(). This methods used to mostly used by developer to combine two collection in single collection, but that's not true here in this post I am going to show the actual difference between this two methods.

Def. from MSDN
Enumerable.Concat  - Concatenates two sequences.
Enumerable.Union    - Produces the set union of two sequences by using the default equality comparer.

If you read the def. carefully you actually find difference between two methods. Now to understand it better way have look to below example
int[] ints1 = { 1, 2, 3 };
int[] ints2 = { 3, 4, 5 };
IEnumerable union = ints1.Union(ints2);
Console.WriteLine("Union");
foreach (int num in union)
{
   Console.Write("{0} ", num);
}
Console.WriteLine();
IEnumerable concat = ints1.Concat(ints2);
Console.WriteLine("Concat");
foreach (int num in concat)
{
   Console.Write("{0} ", num);
}
Output


The output shows that Concat() method just combine two enumerable collection to single one but doesn't perform any operation/ process any element just return single enumerable collection with all element of two enumerable collections.

Union() method return the enumerable collection by eliminating the duplicate i.e just return single element if the same element exists in both enumerable collection on which union is performed.

Important point to Note
  • By this fact we can say that Concat() is faster than Union() because it doesn't do any processing. 
  • But if after combining two collection using Concat() having single collection with too many number of duplicate element and if you want to perform further operation on that created collection takes longer time than collection created using Union() method, because Union() eliminate duplicate and create collection with less elements.

1 comment: