private List<T> TableToList<T>(T obj, DataTable tt)
{
System.Type type = obj.GetType();
List<T> list = new List<T>();
for (int i = 0; i < tt.Rows.Count; i++)
{
T item = (T)Activator.CreateInstance(type); object value; foreach (DataColumn c in tt.Columns)
{
value = tt.Rows[i][c];
if (value != System.DBNull.Value)
{
type.GetProperty(c.ColumnName).SetValue(item, tt.Rows[i][c], null);
}
} list.Add(item);
}
return list;
} 上面的别人的代码,我只想把DATATABLE转换为LIST<string>,DATATABLE已有,请问该方法如合调用呀?DATATABLE里的字段名如何加到LIST里?感谢呀!!LIST<string> aa=?
{
System.Type type = obj.GetType();
List<T> list = new List<T>();
for (int i = 0; i < tt.Rows.Count; i++)
{
T item = (T)Activator.CreateInstance(type); object value; foreach (DataColumn c in tt.Columns)
{
value = tt.Rows[i][c];
if (value != System.DBNull.Value)
{
type.GetProperty(c.ColumnName).SetValue(item, tt.Rows[i][c], null);
}
} list.Add(item);
}
return list;
} 上面的别人的代码,我只想把DATATABLE转换为LIST<string>,DATATABLE已有,请问该方法如合调用呀?DATATABLE里的字段名如何加到LIST里?感谢呀!!LIST<string> aa=?
解决方案 »
- C#与C++代码使用3DES加解密交互,出现解密不成功的尴尬局面
- ComboBox默认选项问题
- 求助:怎样对数组类型的类属性进行赋值操作?
- 如何通过DataGridView更新数据库
- 请问如何使用 checked 关键字作为属性,谢谢!
- c#问题,类文件中如何控制这个文本域?
- 编写C#的窗体时,我想把窗体的四个角给切圆了,给如何实现呢?
- (高手请进)winform中,datagrid控件滚动条问题
- 用EventLog类如何把日志文件写道一个指定目录下的日志文件中?
- 不用学Remoting,序列化就能做分布式应用程序!,灼日-分布式系统平台测试版告诉下载!
- TreeView 控件怎么设置非父节点TreeNode 鼠标Cursor样式
- DevComponents.DotNetBar2.dll 中的控件如何打印呢
{
IList<T> lst= new List<T>();
while (reader.Read())
{
T RowInstance = Activator.CreateInstance<T>();
foreach (PropertyInfo Property in typeof(T).GetProperties())
{
foreach (BindingFieldAttribute FieldAttr in Property.GetCustomAttributes(typeof(BindingFieldAttribute), true))
{
try
{
int Ordinal = reader.GetOrdinal(FieldAttr.FieldName);
if (reader.GetValue(Ordinal) != DBNull.Value)
{
Property.SetValue(RowInstance, Convert.ChangeType(reader.GetValue(Ordinal), Property.PropertyType), null);
}
}
catch
{
break;
}
}
}
lst.Add(RowInstance);
}
return lst;
}
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; }
}
}
这个方法的目的是把datatable转换为 对象的集合
调用方法 先要有对象的定义也就是一条记录的 class,
具体:TableToList<User>((new User()),dt);
看楼主提供的方法:
T 在这里是对象类型,这个方法要求:对象的字段名与表的列名必须对应,可以通过一定的方式来匹配。每一行就是一个对象实例,每一个列(列名与字段名成功匹配)就是一个字段。private List<T> TableToList<T>(T obj, DataTable tt)
{
System.Type type = obj.GetType();
List<T> list = new List<T>();
for (int i = 0; i < tt.Rows.Count; i++)
{
T item = (T)Activator.CreateInstance(type);
//实例化T类型的对象。每行对应一个对象实例。
object value; foreach (DataColumn c in tt.Columns)
{
value = tt.Rows[i][c];//每一列,对应一个字段。
if (value != System.DBNull.Value)
{
type.GetProperty(c.ColumnName).SetValue(item, tt.Rows[i][c], null);
//这个方法,要求对象的字段名与表的列名必须是相同的。所以不需要特殊处理。
}
} list.Add(item);
}
return list;
}
楼主最后的意思是否只去datatable中的列么?
LIST<string> aa=?
这个方法就可以了。//参数:第一个为数据表,第二个是你需要的那列数据的列名 - ColumnName
public static List<string> GetListDataByField(DataTable dtResult, string field)
{
List<string> vals = new List<string>();
if (dtResult.Rows.Count > 0)
{
string val = string.Empty;
foreach (DataRow row in dtResult.Rows)
{
val = row[field].ToString();//如果是其他类型的数据可以在这里做处理。
vals.Add(val);
}
} return vals;
}
//参数:第一个为数据表,第二个是你需要的那列数据的列名 - ColumnName
public static List<string> GetListDataByField(DataTable dtResult, string field)
{
List<string> vals = new List<string>();
if (dtResult.Rows.Count > 0)
{
string val = string.Empty;
foreach (DataRow row in dtResult.Rows)
{
val = row[field].ToString();//如果是其他类型的数据可以在这里做处理。
vals.Add(val);
}
} return vals;
}列是动态生成的,不知道列名怎么办?
{
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;
}
}
用7楼的程序,运行出错了。这是这么用的对吗?myReader有值,感谢呀!!
IList<string> aa = IDataReaderExt.ReaderToList<string>(myReader);
在前面做一个转换。