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
-
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();
-
-
}
-
-
}
-
}
-
Parsed in 0.022 seconds at 45.54 KB/s
Here is the output of console application as Expected.
Hope this will help you..