lid*_*min 5 .net c# generics datatable ado.net
我有一个疑问,有时我将此转换DataTable为List<T>:
List<EDog> lstDogs = (from drRow in dsDogs.Tables[0].AsEnumerable()
select new EDog()
{
intIdDog = drRow.Field<int>("IdDog"),
intIdOwner = drRow.Field<int?>("IdOwner"),
intAge = drRow.Field<int>("Age"),
strName = drRow.Field<string>("Name")
}).ToList();
Run Code Online (Sandbox Code Playgroud)
这工作正常,但现在我正在考虑将它做为通用,以便任何类型的DataSet都可以转换为强类型列表.
我怎么能把它变成通用的呢?也许围绕这部分并创建对象的代表?
new EDog()
{
intIdDog = drRow.Field<int>("IdDog"),
intIdOwner = drRow.Field<int?>("IdOwner"),
intAge = drRow.Field<int>("Age"),
strName = drRow.Field<string>("Name")
}
Run Code Online (Sandbox Code Playgroud)
我试了但是得到了一个错误:
select (lambda) expected....
Run Code Online (Sandbox Code Playgroud)
有什么建议吗?
我之所以需要这个,是因为结果的每个DataRow都需要转换为Entity以便更好地操作.
bni*_*dyc 10
好的,让我们玩得开心:
public static class DataTableExtensions
{
public static List<T> ToGenericList<T>(this DataTable datatable, Func<DataRow, T> converter)
{
return (from row in datatable.AsEnumerable()
select converter(row)).ToList();
}
}
class EDog
{
private int intIdDog;
private int intIdOwner;
private int intAge;
private string strName;
...
public static EDog Converter(DataRow row)
{
return new EDog
{
intIdDog = (int)row["IdDog"],
intIdOwner = (int)row["IdOwner"],
intAge = (int)row["Age"],
strName = row["Name"] as string
};
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
List<EDog> dogs = dsDogs.Tables[0].ToGenericList<EDog>(EDog.Converter);
Run Code Online (Sandbox Code Playgroud)
但是没有足够的乐趣,对吧?那这个呢:
class DataRowKeyAttribute : Attribute
{
private readonly string _Key;
public string Key
{
get { return _Key; }
}
public DataRowKeyAttribute(string key)
{
_Key = key;
}
}
static class DataTableExtensions
{
public static List<T> ToGenericList<T>(this DataTable datatable) where T : new()
{
return (from row in datatable.AsEnumerable()
select Convert<T>(row)).ToList();
}
private static T Convert<T>(DataRow row) where T : new()
{
var result = new T();
var type = result.GetType();
foreach (var fieldInfo in type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
{
var dataRowKeyAttribute = fieldInfo.GetCustomAttributes(typeof (DataRowKeyAttribute), true).FirstOrDefault() as DataRowKeyAttribute;
if (dataRowKeyAttribute != null)
{
fieldInfo.SetValue(result, row[dataRowKeyAttribute.Key]);
}
}
return result;
}
}
class EDog
{
[DataRowKey("IdDog")]
private int intIdDog;
[DataRowKey("IdOwner")]
private int intIdOwner;
[DataRowKey("Age")]
private int intAge;
[DataRowKey("Name")]
private string strName;
...
}
Run Code Online (Sandbox Code Playgroud)
用法:
List<EDog> dogs = dsDogs.Tables[0].ToGenericList<EDog>();
Run Code Online (Sandbox Code Playgroud)
如果您希望获得真正的乐趣,请添加错误处理,请考虑缓存反射数据以提高性能并将字段更改为属性.
这是你想要的东西吗?
public static List<T> ConvertDS<T>(DataSet ds, Converter<DataRow, T> converter)
{
return
(from row in ds.Tables[0].AsEnumerable()
select converter(row)).ToList();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12564 次 |
| 最近记录: |