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});
}
6
/* This is a generic method that will convert any type of DataTable to a List
*
*
* Example : List< Student > studentDetails = new List< Student >();
* studentDetails = ConvertDataTable< Student >(dt);
*
* Warning : In this case the DataTable column's name and class property name
* should be the same otherwise this function will not work properly
*/
public static List<T> ConvertDataTable<T>(DataTable dt)
{
List<T> data = new List<T>();
foreach (DataRow row in dt.Rows)
{
T item = GetItem<T>(row);
data.Add(item);
}
return data;
}
private static T GetItem<T>(DataRow dr)
{
Type temp = typeof(T);
T obj = Activator.CreateInstance<T>();
foreach (DataColumn column in dr.Table.Columns)
{
foreach (PropertyInfo pro in temp.GetProperties())
{
//in case you have a enum/GUID datatype in your model
//We will check field's dataType, and convert the value in it.
if (pro.Name == column.ColumnName){
try
{
var convertedValue = GetValueByDataType(pro.PropertyType, dr[column.ColumnName]);
pro.SetValue(obj, convertedValue, null);
}
catch (Exception e)
{
//ex handle code
throw;
}
//pro.SetValue(obj, dr[column.ColumnName], null);
}
else
continue;
}
}
return obj;
}
21 回答
再次使用3.5你可以这样做:
BRGDS
如果您使用的是.NET 3.5,则可以使用DataTableExtensions.AsEnumerable(扩展方法)然后如果您确实需要
List<DataRow>
而不仅仅是IEnumerable<DataRow>
,则可以调用Enumerable.ToList:要么
使用C#3.0和System.Data.DataSetExtensions.dll,
你可以用
dt.Select()
将返回表中的所有行,作为数据行数组,List
构造函数接受该对象数组作为参数,以便最初填充列表 .如果您只想要返回“ID”int字段中的值列表,您可以使用...
您可以创建扩展功能:
我已经从这个答案添加了一些修改(https://stackoverflow.com/a/24588210/4489664),因为对于可以为空的类型,它将返回异常
一种更“神奇”的方式,不需要.NET 3.5 .
例如,如果
DBDatatable
返回单个Guids列(SQL中的uniqueidentifier),那么您可以使用:DataTable.Select()
并不按照它们在数据表中的顺序给出行 .如果顺序很重要,我觉得迭代datarow集合并形成List是正确的方法,或者你也可以使用
DataTable.Select(string filterexpression, string sort)
的重载 .但是这个重载可能无法处理SQL提供的所有排序(如逐个...) .
这是一个DataTable扩展方法,它将DataTable转换为通用列表 .
https://gist.github.com/gaui/a0a615029f1327296cf8
Usage:
This worked for me: 至少需要.Net Framework 3.5,下面的代码显示DataRow转向Generic.IEnumerable,comboBox1已用于更好的说明 .
使用
System.Data
命名空间然后你会得到.AsEnumerable()
.Output
我们可以使用通用方法将
DataTable
转换为List
,而不是手动将DataTable
转换为List
.注意:
DataTable
的ColumnName
和Type
的PropertyName
应该相同 .调用以下方法:
https://www.nuget.org/packages/AD.GenericConversion/
查看此库以进行转换,您将在此处找到所有类型的转换,例如: -
DataTable到GenericList
DataTable的通用类型
Json到DataTable,通用列表,通用类型
DataTable到Json
您可以使用类似于通用列表的数据通用方法