Friday, June 18, 2010

Union,Except and Intersect operator in Linq

While developing a windows service using Linq-To-SQL i was in need of something that will intersect the two list and return a list with the result. After searching on net i have found three great use full operators in Linq Union,Except and Intersect. Here are explanation of each operator.

Union Operator: Union operator will combine elements of both entity and return result as third new entities.

Except Operator: Except operator will remove elements of first entities which elements are there in second entities and will return as third new entities.

Intersect Operator: As name suggest it will return common elements of both entities and return result as new entities.

Let’s take a simple console application as a example where i have used two string array and applied the three operator one by one and print the result using Console.Writeline. Here is the code for that.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication1
{
 class Program
 {
     static void Main(string[] args)
     {
         string[] a = { "a", "b", "c", "d" };
         string[] b = { "d","e","f","g"};

         var UnResult = a.Union(b);
         Console.WriteLine("Union Result");
         foreach (string s in UnResult)
         {
             Console.WriteLine(s);           
         }

         var ExResult = a.Except(b);
         Console.WriteLine("Except Result");
         foreach (string s in ExResult)
         {
             Console.WriteLine(s);
         }

         var InResult = a.Intersect(b);
         Console.WriteLine("Intersect Result");
         foreach (string s in InResult)
         {
             Console.WriteLine(s);
         }
         Console.ReadLine();
        
     }

 }
}

Here is the output of console application as Expected.

LinqOperators

Hope this will help you.. Stay tuned for more!!


Share:

2 comments:

Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews