Social Icons

Tuesday, February 14, 2012

Converting Your DataTable into List<T>Using Linq Query

This example will help you converting your DataTable into List<T>, this topic is specially helpful for development in silverlight, as DataTables doesnot exist in it, so we need to have to convert DataTable into List<T> or ObservableCollection<T>.

Suppose following is your DataTable
DataTable dtExample = new DataTable("Example");
dtExample.Columns.Add("RollNo");
dtExample.Columns.Add("Name");
dtExample.Columns.Add("Class");


The process of converting above DataTable completes in three steps.
Step1: Make a class having properties with respect to your DataTable Columns, In the Example Table there are three Columns
>> RollNo
>> Name
>> class
So You have to Make the following Class
public class Employees
{
        public String RollNo { get ;  set ;}
        public String Name{ get ;  set ;}
        public String Class{ get ;  set ;}
}

Step2: Make a Function of return type of your above class, that will convert a DataTable Row in List<T> Row, This function will be called in Linq Query in Third Step
private Employees GetEmpDataTableRow(DataRow dr)
{
     Employees oEmp = new Employees();
     oEmp.RollNo = dr["RollNo"].ToString();
     oEmp.Name = dr["Name"].ToString();
     oEmp.Class = dr["Class"].ToString();
     return oEmp ;
}
Step3: In the last you are able to convert your DataTable dtExample into List<Employees&gt. go through the Third Step
List<Employees> LstEmployees = new List<Employees>();
LstEmployees = new List<Employees>(
               (from dRow in dtExample.AsEnumerable()
                select (GetEmpDataTableRow(dRow)))
               );
  

Now LstEmployees is your List of Type List<Employees>, which is converted from DataTable dtExample Hope this will help you and work for you, You can contact in case of any confusion. Thanks for my colleague Mr. Jamal Khan who helped in the above solution

3 comments:

 

Sample text

Sample Text