C# 如何将 DataTable 转换为通用列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/208532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 18:07:26  来源:igfitidea点击:

How do you convert a DataTable into a generic list?

c#genericsdatatable

提问by Iain Holder

Currently, I'm using:

目前,我正在使用:

DataTable dt = CreateDataTableInSomeWay();

List<DataRow> list = new List<DataRow>(); 
foreach (DataRow dr in dt.Rows)
{
    list.Add(dr);
}

Is there a better/magic way?

有没有更好/神奇的方法?

采纳答案by Jon Skeet

If you're using .NET 3.5, you can use DataTableExtensions.AsEnumerable(an extension method) and then if you really need a List<DataRow>instead of just IEnumerable<DataRow>you can call Enumerable.ToList:

如果你使用 .NET 3.5,你可以使用DataTableExtensions.AsEnumerable(一个扩展方法),然后如果你真的需要一个List<DataRow>而不是IEnumerable<DataRow>你可以调用Enumerable.ToList

IEnumerable<DataRow> sequence = dt.AsEnumerable();

or

或者

using System.Linq;
...
List<DataRow> list = dt.AsEnumerable().ToList();

回答by Kibbee

You could use

你可以用

List<DataRow> list = new List<DataRow>(dt.Select());

dt.Select()will return all rows in your table, as an array of datarows, and the Listconstructor accepts that array of objects as an argument to initially fill your list with.

dt.Select()将返回表中的所有行,作为数据行数组,并且List构造函数接受该对象数组作为参数来初始填充列表。

回答by Marc Gravell

With C# 3.0 and System.Data.DataSetExtensions.dll,

使用 C# 3.0 和 System.Data.DataSetExtensions.dll,

List<DataRow> rows = table.Rows.Cast<DataRow>().ToList();

回答by Jon Skeet

A more 'magic' way, and doesn't need .NET 3.5.

一种更“神奇”的方式,不需要 .NET 3.5。

If, for example, DBDatatablewas returning a single column of Guids (uniqueidentifier in SQL) then you could use:

例如,如果DBDatatable返回单列 Guids(SQL 中的唯一标识符),那么您可以使用:

Dim gList As New List(Of Guid)
gList.AddRange(DirectCast(DBDataTable.Select(), IEnumerable(Of Guid)))

回答by user_v

DataTable.Select()doesnt give the Rows in the order they were present in the datatable.

DataTable.Select()没有按照它们在数据表中的顺序给出行。

If order is important I feel iterating over the datarow collection and forming a List is the right way to go or you could also use overload of DataTable.Select(string filterexpression, string sort).

如果顺序很重要,我觉得迭代数据行集合并形成一个 List 是正确的方法,或者您也可以使用DataTable.Select(string filterexpression, string sort).

But this overload may not handle all the ordering (like order by case ...) that SQL provides.

但是这种重载可能无法处理 SQL 提供的所有排序(例如按案例排序...)。

回答by Guilherme Duarte

Again, using 3.5 you may do it like:

同样,使用 3.5 你可以这样做:

dt.Select().ToList()

BRGDS

BRGDS

回答by darshan pandya

List<Employee> emp = new List<Employee>();

//Maintaining DataTable on ViewState
//For Demo only

DataTable dt = ViewState["CurrentEmp"] as DataTable;

//read data from DataTable 
//using lamdaexpression


emp = (from DataRow row in dt.Rows

   select new Employee
   {
       _FirstName = row["FirstName"].ToString(),
       _LastName = row["Last_Name"].ToString()

   }).ToList();

回答by Morteza

using System.Data;


var myEnumerable = myDataTable.AsEnumerable();

List<MyClass> myClassList =
    (from item in myEnumerable
     select new MyClass{
         MyClassProperty1 = item.Field<string>("DataTableColumnName1"),
         MyClassProperty2 = item.Field<string>("DataTableColumnName2")
    }).ToList();

回答by Stuart

If you just want a list of values from the "ID" int field returned, you could use...

如果您只想返回“ID”int 字段中的值列表,您可以使用...

List<int> ids = (from row in dt.AsEnumerable() select Convert.ToInt32(row["ID"])).ToList();

回答by syed ali abbas

DataTable dt;   // datatable should contains datacolumns with Id,Name

List<Employee> employeeList=new List<Employee>();  // Employee should contain  EmployeeId, EmployeeName as properties

foreach (DataRow dr in dt.Rows)
{
    employeeList.Add(new Employee{EmployeeId=dr.Id,EmplooyeeName=dr.Name});
}