Blogger news

Blogger templates

Monday, November 14, 2011

Linq NOT IN

This will explain how i can take values from a List which is not there another List.

I have to List of type Employee which is shown below.

List list1 = new List
{
new Employee{EmpID= 1,Name="Sreelas"},
new Employee{EmpID= 2,Name="Serosh"},
new Employee{EmpID= 3,Name="Sanjay"},
new Employee{EmpID= 4,Name="Mohandas"}
};

List list2 = new List
{
new Employee{EmpID= 1,Name="Sreelas"},
new Employee{EmpID= 2,Name="Serosh"},
new Employee{EmpID= 3,Name="Sanjay"},
new Employee{EmpID= 4,Name="Mohandas"},

new Employee{EmpID= 5,Name="Shareef"},
new Employee{EmpID= 6,Name="Ansar"},
new Employee{EmpID= 7,Name="Binoj"},
new Employee{EmpID= 8,Name="Sooraj"}
};

In first list i dont have data for employe id 5,6,7,8 and i want to fetch those datas. Explaining query to get the same both in lambda expression and in query syntax.

Query Syntax

var query = from c in list2
where !(from o in list1
select o.EmpID).Contains(c.EmpID)
select c;

foreach (var employee in query)
{
Console.WriteLine("Employee ID: {0}\nName: {1}", employee.EmpID, employee.Name);
Console.WriteLine("*****************************************************************");
}

Lambda Expression

var lambda = list2.Where(c => !list1.Select(o => o.EmpID).Contains(c.EmpID)).ToList();

foreach (var employee in lambda)
{
Console.WriteLine("Employee ID: {0}\nName: {1}", employee.EmpID, employee.Name);
Console.WriteLine("*****************************************************************");
}


Complete code is given below

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

namespace LinqNotIN
{
class Program
{
static void Main(string[] args)
{
List list1 = new List
{
new Employee{EmpID= 1,Name="Sreelas"},
new Employee{EmpID= 2,Name="Serosh"},
new Employee{EmpID= 3,Name="Sanjay"},
new Employee{EmpID= 4,Name="Mohandas"}
};

List list2 = new List
{
new Employee{EmpID= 1,Name="Sreelas"},
new Employee{EmpID= 2,Name="Serosh"},
new Employee{EmpID= 3,Name="Sanjay"},
new Employee{EmpID= 4,Name="Mohandas"},

new Employee{EmpID= 5,Name="Shareef"},
new Employee{EmpID= 6,Name="Ansar"},
new Employee{EmpID= 7,Name="Binoj"},
new Employee{EmpID= 8,Name="Sooraj"}
};

var query = from c in list2
where !(from o in list1
select o.EmpID).Contains(c.EmpID)
select c;

var lambda = list2.Where(c => !list1.Select(o => o.EmpID).Contains(c.EmpID)).ToList();

foreach (var employee in lambda)
{
Console.WriteLine("Employee ID: {0}\nName: {1}", employee.EmpID, employee.Name);
Console.WriteLine("*****************************************************************");
}
Console.ReadKey();
}
}

public class Employee
{
public int EmpID { get; set; }

public string Name { get; set; }
}
}

2 comments:

Post a Comment