Follow by Email

Thursday, 18 October 2012

Converting DataTable into ListUsing Linq Query in asp.net

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 
?
1
2
3
4
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 
?
1
2
3
4
5
6
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 
?
1
2
3
4
5
6
7
8
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 
?
1
2
3
4
5
6
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.

0 comments:

Post a Comment


                                                            

 
Design by Abhinav Ranjan Sinha