public static T ToGetInformation<T>(this DataTable dt, string RowName) where T:new()
{
T RowValue ;
RowValue = dt.AsEnumerable().Where(w => { w.Field<T>(RowName); return true; }).Select(s => s).FirstOrDefault();
return RowValue;
}
现在的问题是 Select(s => s) 这边返回的数据类型无法强制转化为 T类型
谁遇到过这个问题,求解决
如何转化数据该类型 返回T类型的数据
指明类型是没问题的 private T MM<T>() where T: new()
{
List<T> list = new List<T>();
T t = list.Where(x=>x!=null).Select(v => v).FirstOrDefault();
return t;
}
我这方法实际上实现的功能是 任何一个DataTable点这个扩展方法传入需要返回的类型以及这个DataTable中的某一列的列名,可以返回该列中该类型的值(这个DataTable只有一行)
这么写 public static T ToGetInformation<T>(this DataTable dt, string RowName) where T : new()
{
T RowValue;
RowValue = dt.AsEnumerable().First().Field<T>(RowName);
return RowValue;
}
{
T RowValue ;
RowValue = dt.AsEnumerable().Where(w => w.Field<T>(RowName) is T; ).Select(s => sw.Field<T>(RowName)).FirstOrDefault();
return RowValue;
}
??????为啥不直接firstordefault??
public static List<T> DataTableConvertList<T>(this DataTable table) where T : class,new()
{
List<T> list = new List<T>();
Type t=typeof(T);
if (table == null || table.Rows.Count == 0)
{
throw new Exception("DataTable is null ");
}
foreach (DataRow row in table.Rows)
{
T obj = new T();
foreach (DataColumn column in table.Columns)
{
PropertyInfo property = t.GetProperty(column.ColumnName);
Type propertyType = property.PropertyType;
string value = row[column].ToString();
if (!property.CanWrite)
{
// throw new Exception("Property is readOnly");
continue;
}
if (propertyType == typeof(int?) || propertyType == typeof(int))
{
int tempVlaue;
if (!int.TryParse(value, out tempVlaue))
{
tempVlaue = 0;
}
property.SetValue(obj, tempVlaue, null);
continue;
}
if (propertyType == typeof(bool) || propertyType == typeof(bool?))
{
bool tempVlaue=false;
if (value == "是" || value == "1" || value.ToLower() == "true")
{
tempVlaue = true;
}
property.SetValue(obj, tempVlaue, null);
continue;
}
property.SetValue(obj, value, null);
}
list.Add(obj);
}
return list;
}我也写了一个,还有很多类型没考虑到,其中烦一点的应该是自定义类型和枚举的转换.比如DataTable的ColumnName 是 Product.ProductPrice.BasicPrice 这种转换应该需要类都继承一个基类才能做到
要么先取第一行再取列值
dt.AsEnumeralbe().First().Field<T>("colName")
要么先取列值再取第一行
dt.AsEnumerable().Select(row=>row.Filed<T>("colName")).First()