LINQ – choosing between Concat() and Union()

In Linq To Objects, there are two ways you can join two sequences together, using either Concat() or Union(), and as I was wondering how the two differs I came across this post:

http://weblogs.asp.net/fbouma/archive/2009/03/04/choose-concat-over-union-if-possible.aspx

The main thing to take away from this article is:

“If you care about the duplicates, Union() is necessary. However, in the case where you can’t have duplicates in the second sequence or you don’t care, Concat() is a better choice.”

Thinking in T-SQL terms:

Concat() = UNION ALL

Union() = UNION

Joining two sequences using Union()

If by some chance you’re looking to join two potentially duplicated lists together, and you don’t want duplicates in the resulting list, see this question on StackOverflow and see Jon Skeet’s answer for a nice and clean way to do this:

http://stackoverflow.com/questions/590991/merging-two-ienumerablets

1 thought on “LINQ – choosing between Concat() and Union()”

  1. I think the sentence you quote has been altered in the original to make its intent clearer: “If you do not want duplicates in the second sequence to appear in the resulting sequence, Union() is necessary. However, in the case where it’s impossible to have duplicates in the second sequence or you don’t care if duplicates in the second sequence appear in the resulting sequence, Concat() is a better choice.”

Leave a Comment

Your email address will not be published. Required fields are marked *