LINQ To DataTable

Sorry for not choosing bulk insert / update again in this post. I select this topic LINQ to DataTable because I think this is a very interesting topic to post. In one of the project  in my company, I saw many DataTable operations using the old style – dt.Select() method to filter DataRows. There are lots of chances of errors at run time because all conditions are simple strings written in “.Select()” method.
If you have LINQ support in your project then LINQ to DataTable is the best way to filtering datarows from DataTable. This will also reduce run time errors and I also found that LINQ takes less time to execute then Select() method if amount of rows in DataTable is more.
So, let’s start by creating one temporary DataTable. We will use this DataTable to understand LINQ to DataTable.

Create new DataTable
// Create new DataTable
DataTable dtOrders = new DataTable();

// Add columns you need
dtOrders.Columns.Add("OrderID", typeof(int));
dtOrders.Columns.Add("OrderDate", typeof(DateTime));
dtOrders.Columns.Add("ShippedDate", typeof(DateTime));
dtOrders.Columns.Add("ShipName", typeof(string));
dtOrders.Columns.Add("ShipAddress", typeof(string));
dtOrders.Columns.Add("ShipCity", typeof(string));
dtOrders.Columns.Add("ShipRegion", typeof(string));
dtOrders.Columns.Add("ShipPostalCode", typeof(string));
dtOrders.Columns.Add("ShipCountry", typeof(string));



Fill sample data
// Create new DataRow
DataRow drOrder = null;

// Loop on Customers table in database to add required values in new DataTable
foreach (Orders o in Orders.ToArray()) // Here Orders is table from Northwind database
{
// Initialize DataRow variable
drOrder = dtOrders.NewRow();

// Set required values in DataRow
drOrder["OrderID"] = o.OrderID;
drOrder["OrderDate"] = o.OrderDate;
drOrder["ShippedDate"] = o.ShippedDate == null ? DateTime.MinValue : o.ShippedDate;
drOrder["ShipName"] = o.ShipName;
drOrder["ShipAddress"] = o.ShipAddress;
drOrder["ShipCity"] = o.ShipCity;
drOrder["ShipRegion"] = o.ShipRegion;
drOrder["ShipPostalCode"] = o.ShipPostalCode;
drOrder["ShipCountry"] = o.ShipCountry;

// Add DataRow to DataTable
dtOrders.Rows.Add(drOrder);
}



Fetch rows from DataTable using LINQ
var drAll = from orders in dtOrders.AsEnumerable()
where orders.Field<DateTime>("ShippedDate") == new DateTime(1996, 7, 16)
select orders;

// Write below statement to assign result of above LINQ to new DataTable 
// DataTable dt = drAll.CopyToDataTable<DataRow>();



To understand more about “.CopyToDataTable()” method please visit http://msdn.microsoft.com/en-us/library/bb386921.aspx

Display result data
// Display result data
foreach (var order in drAll)
{
Console.WriteLine(String.Format("{0} | {1}", order["OrderID"], order["ShippedDate"]));
}



Sorting in DataTable using LINQ
// Order by ascending 
var drAll1 = from orders in dtOrders.AsEnumerable()
orderby orders.Field<DateTime>("ShippedDate") ascending
select orders;

// Order by descending
var drAll2 = from orders in dtOrders.AsEnumerable()
orderby orders.Field<DateTime>("ShippedDate") descending
select orders; 



Group by in DataTable using LINQ
var drAll = from orders in dtOrders.AsEnumerable()
group orders by orders.Field<string>("ShipRegion") into g
select new { ShipRegion = g.Key, Group = g };



Instead of simple DataTable, you can also use typed dataset in your project. This will convert all your columns into property so in this case, instead of using “.Field<DateTime>(“ShippedDate”)” you can simply access “ShippedDate” property of your typed dataset. ex. where orders.ShippedDate == new DateTime(1996, 7, 16) where “.ShippedDate” is a columns of your typed dataset with data type DateTime.


Comments

Popular posts from this blog

Lambda Expressions In Entity Framework

LINQ To Entity Framework Tutorial

Select Columns From Multiple Tables Using LINQ