Saturday, January 17, 2015

How to search into a DataTable without a loop in C#?

Sometimes we are in a need to compare few values or filter records from our DataTable to get the exact result. We use to follow the technique since the last decade to looping into DataTable then compare each and every row to get the desired result. This post will help you to avoid loops and provide an appropriate method to achieved your target.

Basically, there are two ways to filter the records; by considering the below example.

Let's suppose, you have a DataTable with the following Definition & Data.

Customer Table (dtCustomer)

Id    FirstName    LastName   EmailAddress                   Address
1     Abdul            Wahab           abdulwahab@xyz.com      Al Nahda Street
2     Abdul            Qayyuum      abdulqayuum@xyz.com    Al Sufoof Street
3     George           Adam           georgea@xyz.com             Al Nahda Street
4     Hemant          Singh            hSign@xyz.com                Jumerah Street
5     Muhammad   Ali                mali@xyz.com                   City Street

We are requiring two types of data,

1. Get all customers, who are residing near 'Al Nahda Street'.
2. Get all customers, who are residing near 'Al Nahda Street' & their first name starts with 'Abdul'.

Now, there are two ways to get the records: one is with the DataView & the other one with Linq.

Dataview Method

var dview = new DataView(dtCustomer);

Requirement 1

dview.RowFilter= "Address like '%Al Nahda%'";
var dtResult1 = dview.ToTable();

Requirement 2

dview.RowFilter= "Address like '%Al Nahda%' and FirstName like '%Abdul%' ";
var dtResult2 = dview.ToTable();

*dtResult1 & dtResult2 has the desired results.*

Linq Method (Lamda expression & Predicate) 

Requirement 1

var lst1= dt.AsEnumerable().Where(delegate(DataRow s){ return s["Address"].ToString().Contains("Nahda")  ; }).ToList();

OR 

var lst1= dt.AsEnumerable().Where(s=> { return s["Address"].ToString().Contains("Nahda") ; }).ToList();

OR

var lst1= dt.AsEnumerable().Where(s=> s["Address"].ToString().Contains("Nahda") ; }).ToList();

Requirement 2

var lst2= dt.AsEnumerable().Where(delegate(DataRow s){ return s["Address"].ToString().Contains("Nahda") && s["Name"].ToString().Contains("Abdul") ; }).ToList();

OR 

var lst2= dt.AsEnumerable().Where(s=> { return s["Address"].ToString().Contains("Nahda") && s["Name"].ToString().Contains("Abdul") ; }).ToList();


*lst1 & lst1 have the desired results, with DataRow as a type*.


Consequently, from the above two methods everyone can filter their records without using a loop.
Happy Coding....! :)