LINQ – choosing between Concat() and Union()

Yan Cui

I help clients go faster for less using serverless technologies.

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


 

Whenever you’re ready, here are 4 ways I can help you:

  1. If you want a one-stop shop to help you quickly level up your serverless skills, you should check out my Production-Ready Serverless workshop. Over 20 AWS Heroes & Community Builders have passed through this workshop, plus 1000+ students from the likes of AWS, LEGO, Booking, HBO and Siemens.
  2. If you want to learn how to test serverless applications without all the pain and hassle, you should check out my latest course, Testing Serverless Architectures.
  3. If you’re a manager or founder and want to help your team move faster and build better software, then check out my consulting services.
  4. If you just want to hang out, talk serverless, or ask for help, then you should join my FREE Community.

 


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 *