About Me

Monday, November 28, 2011

How to use LINQ with DataTable

LINQ came into .NET developers life and at present moment I can't imagine my life without it. Actually, I can imagine, but it will be horrible.

Few days ago I had to modify some old project that has ADO.NET code in it.
Unfortunately we still have to work with all that datasets and datatables from time to time.
However, we can make life easier if start to use LINQ for operating with that. Its really easy.

First of all you need to add a reference to System.Data.DatasetExtensions library from a project where you going to use LINQ.
That library, as you may see from the name, contains some extension methods that allows to write LINQ queries directly on DataTables.

public DeviceFamilyInfo Get(int deviceFamilyId)
{
 DataSet rawFamilyInfo = DBMethods.GetDeviceFamily(deviceFamilyId);
 EnumerableRowCollection tblDevices = rawFamilyInfo.Tables[1].AsEnumerable();

 List>DeviceInfo> devices = GetDevicesList(tblDevices);

 return rawFamilyInfo.Tables[0].AsEnumerable()
  .Select(f =< 
   new DeviceFamilyInfo(devices)
    {
     Id = (int) f["Id"], 
     FamilyName = (string) f["Name"]
    }).First();
}

As you may see, the secret in converting datatable into IEnumerable by calling of AsEnumerable() method from the referenced library.
After that conversion, you can do with your data whatever you want. In my case, i just wrote a simple mapper that converts a DataTable into  instance of DeviceFamilyInfo class

No comments:

Post a Comment