How to achieve UNION ALL and UNION in LINQ

In one of my application, I came to a situation where I had to use UNION ALL like functionality for two enumerable list by using LINQ. So in today’s post we’ll learn about how we can achieve UNION and UNION ALL like functionality using LINQ. You can do a UNION operation using the Union method in LINQ and UNION ALL operation using the Concat method.

Let’s see this practically –

First we will learn about Union method.

static void Main(string[] args)
{
	var productsFromMicrosoft = new List<string>
	{
		"Visual Studio",
		"MS Office",
		"Xbox",
		"Mail Service"  // <-- This product is in both list
	};

	var productsFromGoogle = new List<string>
	{
		"Google Chrome",
		"Mail Service",  // <-- This product is in both list
		"Blogger"
	};

	var unionList = productsFromMicrosoft.Union(productsFromGoogle).ToList();

	Console.WriteLine(unionList);
}

UnionList

So as expected, UNION method excludes duplicates from the return set.

Now we will see Concat operator.

static void Main(string[] args)
{
	var productsFromMicrosoft = new List<string>
	{
		"Visual Studio",
		"MS Office",
		"Xbox",
		"Mail Service"  // <-- This product is in both list
	};

	var productsFromGoogle = new new List<string>
	{
		"Google Chrome",
		"Mail Service",  // <-- This product is in both list
		"Blogger"
	};

	var unionAllList = productsFromMicrosoft.Concat(productsFromGoogle).ToList();

	foreach (var product in unionAllList)
	{
		Console.WriteLine(product);
	}
}

UnionAllList

The Concat method differs from the Union method because the Concat() method returns all the original elements in the input sequences. The Union method returns only unique elements.

Reference Link:

That’s it folks. Hope you like this post.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s