I’ve been working on my old code which was just migrated from VS2005 to VS2010. In my version i could not leverage the LINQ and i was using lots of DataSets and DataTable by querying my stored procedures.
Now that my code has been upgraded to .Net 4 and VS2010 i wanted to leverage the LINQ instead of FOR Loops to make my code look cleaner, at the same time; i also did not want to break my existing functionalities So my Business layer can use LINQ to filter/sort/group data from DataSet and can still return DataSet to my presentation layer in order to maintain the integrity. There’s no straight way to use LINQ on DataSet and return DataSet, So i made a small extension method.
public static DataTable ToDataTable<T>(this IList<DataRow> data)
{
DataTable table = new DataTable();
if (data.Count > 0)
{
table = ((DataRow)data[0]).Table.Clone();
foreach (DataRow drData in data)
{
table.Rows.Add(drData.ItemArray);
}
}
return table;
}
Here’s how we use the ToDataTable extension:
private DataTable FilterCustomersByName(DataSet dts, string CustomerNames)
{
var Data = (from t in dts.Tables[0].AsEnumerable()
where CustomerNames.Contains(t.Field<string>("CUSTOMER_NAME").ToString())
select t).ToList().ToDataTable<DataRow>();
return Data;
}
enjoy!!
No comments:
Post a Comment