Monday, July 6, 2009

LINQ: How to use SQL's Not In query in LINQ

Querying data using "Not In" operator is very common for any programmer who involved in database layer of any application.

"Not In" operator is generally used to fetch all records/data in a table whose field(column) value does not match the given list of values. Assume you have Employee Table and it has a field called city, where the cities added are "A","B","C","D" and "E". Now if you want to fetch all the employees who are not living in cities "B", "C" and "E", in SQL you write query as below

Select * from employee where city not in ("B","C","E").

We can do the same in LINQ using "Except(List listObject)" method.

Generally we will use in-memory objects between different layers in our applications and in certain times we need to fetch a group of objects to implement a specific functionalities in the business model. Infact i had a list of 100 or more objects and i want to fetch a random of 10 objects based on a condition.

I explored different options like having a Hashtable or dictionary object and i'm not interested to create one collection just for this sake.
When i was googling for a solution i came to know about this method available in .Net 3.5 that simply solves my filter criteria without using foreach inside foreach....

Well here is the code which is similar to "Not In" operator in SQL.
Create a List of dummy data...

IList dataList = new List();
dataList.Add("1");
dataList.Add("2");
dataList.Add("3");
dataList.Add("4");
dataList.Add("5");
dataList.Add("6");

The below code fetch the top 2 records from the list and puts it into a new List

var topList = (from data in dataList
select data).Take(2);

Now to select a records/objects that does not match the toplist(data), simply we need to write the below code.

var filteredList = dataList.Except(topList);
The Except method will create a new list from dataList by excluding the records/data matching the topList.
Now filteredList will have only records/data that of "3,4,5 and 6"

This method really helps me in a situation where i dont know the filter criteria at compile time, size of the list, size of the filter list. On counting performance, this way is far better comparing to foreach





No comments:

Post a Comment