How C # generates a generic list or a dynamic type list based on a DataTable

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.