读书人

怎么将DataTable转换为list

发布时间: 2013-09-06 10:17:17 作者: rapoo

如何将DataTable转换为list?
想写一个方法 传入任何DataTable都转换为List<> 每一条记录为一个对象 存入list中 类似linq里那种 求思路~
[解决办法]
http://www.cnblogs.com/chenliang0724/archive/2009/05/20/1471780.html
[解决办法]


public static IList<T> ConvertToModel(DataTable dt)
{
// 定义集合
IList<T> ts = new List<T>();

// 获得此模型的类型
Type type = typeof(T);

string tempName = "";

foreach (DataRow dr in dt.Rows)
{
T t = new T();

// 获得此模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();

foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name;

// 检查DataTable是否包含此列
if (dt.Columns.Contains(tempName))
{
// 判断此属性是否有Setter
if (!pi.CanWrite) continue;

object value = dr[tempName];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}

ts.Add(t);
}

return ts;

}



[解决办法]
楼上的方法需要放在一个带有new()约束的类里
或者方法签名改成这样
public static IList<T> ConvertToModel<T>(DataTable dt) where T : new()
{
}
[解决办法]
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

namespace ssss

/// <summary>
/// Summary description for ConvertEntity1
/// </summary>
public static class IDataReaderExt



public static T ReaderToModel<T>(this IDataReader dr)

// try
// {
using (dr)

T model = Activator.CreateInstance<T>();
if (dr.Read())

Type modelType = typeof(T);
int count = dr.FieldCount;
for (int i = 0; i < count; i++)

// string n = dr.GetName(i);
if (!IsNullOrDBNull(dr[i]))

PropertyInfo pi = modelType.GetProperty(dr.GetName(i), BindingFlags.GetProperty
[解决办法]
BindingFlags.Public
[解决办法]
BindingFlags.Instance
[解决办法]
BindingFlags.IgnoreCase);
if (pi != null)

pi.SetValue(model, HackType(dr[i], pi.PropertyType), null);
// pi.SetValue(model, Convert.ChangeType(dr[i], pi.PropertyType), null);
// pi.SetValue(model,HackType<pi.PropertyType)(dr[i], pi.PropertyType), null);



return model;


return default(T);
// }
// catch (Exception ex)
// {
// return default(T);
// }


public static IList<T> ReaderToList<T>(this IDataReader dr)

using (dr)

List<T> list = new List<T>();
Type modelType = typeof(T);
int count = dr.FieldCount;
while (dr.Read())

T model = Activator.CreateInstance<T>();

for (int i = 0; i < count; i++)

if (!IsNullOrDBNull(dr[i]))
{//GetPropertyName
PropertyInfo pi = modelType.GetProperty(dr.GetName(i), BindingFlags.GetProperty
[解决办法]
BindingFlags.Public


[解决办法]
BindingFlags.Instance
[解决办法]
BindingFlags.IgnoreCase);
if (pi != null)

pi.SetValue(model, HackType(dr[i], pi.PropertyType), null);
// pi.SetValue(model, Convert.ChangeType(dr[i], pi.PropertyType), null);



list.Add(model);

return list;



private static object HackType<T>(object value, T conversionType) where T : Type

// return value == null ? new T() : (T)value;

value = IsNullOrDBNull(value) ? default(T) : (T)value;

if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))

if (value == null)
return null;
System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
conversionType = (nullableConverter.UnderlyingType as T);

return Convert.ChangeType(value, conversionType);


//这个类对可空类型进行判断转换,要不然会报错
private static object HackType(object value, Type conversionType)

if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))

if (value == null)
return null;

System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
conversionType = nullableConverter.UnderlyingType;

return Convert.ChangeType(value, conversionType);



private static bool IsNullOrDBNull(object obj)

return (obj == null
[解决办法]
(obj is DBNull)) ? true : false;




//取得DB的列对应bean的属性名

private static string GetPropertyName(string column)




column = column.ToLower();

string[] narr = column.Split(_);

column = "";

for (int i = 0; i < narr.Length; i++)


if (narr[i].Length > 1)


column += narr[i].Substring(0, 1).ToUpper() + narr[i].Substring(1);



else


column += narr[i].Substring(0, 1).ToUpper();





return column;






[解决办法]
 IList<类名A> ConvertToModel<类名A>(datatable)
这样调用就行了
[解决办法]
引用:
C# code

public static IList<T> ConvertToModel(DataTable dt)
{
// 定义集合
IList<T> ts = new List<T>();

// 获得此模型的类型
Type type = typeof(T);

string tempName = "";

foreach (DataR……


这个方法可以实现楼主需求。
楼主“每个实例里的字段值都是null”,可能是因为DataTable里的列名和类的属性名没对应上,或是类属性没设置setter访问器
[解决办法]
楼主需要为每个字段设置属性:
public string _Userid;
public string _Username;

public string Userid
{
get{return _Userid;}
set//没这个的话,无法将值放入类实例
{
_Userid=value;
}
}
public string Username
{
get{return _Username;}
set//没这个的话,无法将值放入类实例
{
_Username=value;
}
}

[解决办法]
IList<UserInfo> list = ConverToModel<UserInfo>(tb);


解释下上面的那个方法吧,先是用typof得到UserInfo的实例,然后通过tb的column和userinfo的字段对比,并且把userinfo的属性赋值,通过反射赋值的。反射出userinfo的属性,对每个属性赋值。放进去的时候是空的,返回的时候就是userinfo反省集合。

读书人网 >C#

热点推荐