Background: In the project, SQL statement retrieval returns a DataTable, and then, based on the results of the search, this article describes how to quickly generate a generic list of DataTable returns.
Assume that the following student classes exist:
1 Public classStudent2 {3 Public intID {Get;Set; }4 Public stringStuname {Get;Set; }5 Public stringCitycode {Get;Set; }6}
The following data table student exist:
1. Generic list, its C # code is as follows:
1 da. Fill (DT);2List<student> Liststu =NULL;3 if(dt. Rows.Count >0)4 {5Liststu = dt. AsEnumerable (). Select (row =NewStudent () {ID = Convert.ToInt32 (row["ID"]), Stuname = row["Stuname"]. ToString (), Citycode = row["Citycode"]. ToString ()}). ToList ();6}
Note the use of Select and ToList () in the code.
2. Dynamic type list, its C # code is as follows:
1 da. Fill (DT);2 if(dt. Rows.Count >0)3 {4 varrows = dt. AsEnumerable (). Select (row =New{ID = Convert.ToInt32 (row["ID"]), Stuname = row["Stuname"]. ToString (), Citycode = row["Citycode"]. ToString ()}). ToList ();5 foreach(varIteminchrows)6 {7 Console.WriteLine (item. Stuname);8 }9}
Each element of rows is an object of an anonymous type.
How C # generates a generic list or a dynamic type list based on a DataTable