Click here to Skip to main content
15,883,877 members
Articles / Programming Languages / C#
Tip/Trick

Concat() vs Union()

Rate me:
Please Sign up or sign in to vote.
4.67/5 (2 votes)
30 Oct 2012CPOL1 min read 27.8K   7  
Concat() vs Union()

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<tsource>  - Concatenates two sequences.

Enumerable.Union<tsource>    - 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<int> union = ints1.Union(ints2);
Console.WriteLine("Union");
foreach (int num in union)
{
   Console.Write("{0} ", num);
}
Console.WriteLine();
IEnumerable<int> concat = ints1.Concat(ints2);
Console.WriteLine("Concat");
foreach (int num in concat)
{
   Console.Write("{0} ", num);
}
</int></int>

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.  

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India

Microsoft C# MVP (12-13)



Hey, I am Pranay Rana, working as a Team Leadin MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.

For me def. of programming is : Programming is something that you do once and that get used by multiple for many years

You can visit my blog


StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr

Awards:



Comments and Discussions

 
-- There are no messages in this forum --