Union,Except and Intersect operator in Linq

Posted by Jalpesh P. Vadgama on ASP.net Weblogs See other posts from ASP.net Weblogs or by Jalpesh P. Vadgama
Published on Thu, 17 Jun 2010 20:14:28 GMT Indexed on 2010/06/17 20:24 UTC
Read the original article Hit count: 467

Filed under:
|
|
|
|

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.

C#, using GeSHi 1.0.8.6
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6.  
  7. namespace ConsoleApplication1
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             string[] a = { "a", "b", "c", "d" };
  14.             string[] b = { "d","e","f","g"};
  15.  
  16.             var UnResult = a.Union(b);
  17.             Console.WriteLine("Union Result");  
  18.             foreach (string s in UnResult)
  19.             {
  20.                 Console.WriteLine(s);             
  21.             }
  22.  
  23.             var ExResult = a.Except(b);
  24.             Console.WriteLine("Except Result");
  25.             foreach (string s in ExResult)
  26.             {
  27.                 Console.WriteLine(s);
  28.             }
  29.  
  30.             var InResult = a.Intersect(b);
  31.             Console.WriteLine("Intersect Result");
  32.             foreach (string s in InResult)
  33.             {
  34.                 Console.WriteLine(s);
  35.             }
  36.             Console.ReadLine(); 
  37.              
  38.         }
  39.     
  40.     }
  41. }
  42.  
Parsed in 0.022 seconds at 45.54 KB/s

Here is the output of console application as Expected.

LinqOperators

Hope this will help you..

Technorati Tags: ,,,,
Shout it

© ASP.net Weblogs or respective owner

Related posts about ASP.NET

Related posts about c#.net