将数据表转换为字典<;T1、T2>;使用泛型和扩展方法
本文关键字:gt 泛型 方法 扩展 T2 T1 转换 数据表 字典 lt | 更新日期: 2023-09-27 18:24:52
我正试图从DataTable创建一个Dictionary。目前,我首先创建一个IList,然后循环列表,并将它们添加到字典中,根据具体情况分别指定列表中结果对象的主键属性。
我想知道这是否可以使用泛型来完成。
我目前有以下代码,无法编译或工作:
public static IDictionary<T1, T2> ToDictionary<T1,T2>(this DataTable table) where T2 : new()
{
IList<PropertyInfo> properties = GetPropertiesForType<T2>();
IDictionary<T1,T2> result = new Dictionary<T1,T2>();
Dictionary<string, int> propDict = GetPropertyDictionary(properties, table);
T1 PK;
foreach (var row in table.Rows)
{
var item = CreateDictItemFromRow<T2>((DataRow)row, properties, propDict);
result.Add(item. item); //not sure here
}
return result;
}
本质上,我想称之为:
Dictionary<int, MyDBClass> Items = DataTable.ToDictionary<int,MyDBClass>();
或
Dictionary<Int16,MyDBClass> Items = DataTable.ToDictionary<Int16, MyDBClass>();
我假设在某个地方我需要将主键属性名传递给这个函数。如果失败,我可以安全地假设Datatable中的第一列包含主键(尽管假设它总是int(可能是短或字节)是不安全的)。
我也知道使用LINQ可以很容易地做到这一点,但我在C#中还没有走那么远,希望更改现有的应用程序。
感谢您的帮助。
希望这能有所帮助。
public static class Extensions
{
public static Dictionary<TKey, TRow> TableToDictionary<TKey,TRow>(
this DataTable table,
Func<DataRow, TKey> getKey,
Func<DataRow, TRow> getRow)
{
return table
.Rows
.OfType<DataRow>()
.ToDictionary(getKey, getRow);
}
}
public static void SampleUsage()
{
DataTable t = new DataTable();
var dictionary = t.TableToDictionary(
row => row.Field<int>("ID"),
row => new {
Age = row.Field<int>("Age"),
Name = row.Field<string>("Name"),
Address = row.Field<string>("Address"),
});
}
顺便说一句,您需要包含程序集System.Data.DataSetExtensions.dll才能使用Field扩展方法。
如果你还有其他问题,请毫不犹豫地问。
在base2的大力帮助下,我完成了以下方法:
public static IDictionary<TKey, T> ToDictionary<TKey, T>(this DataTable table, Func<DataRow,TKey> getKey) where T : new()
{
IList<PropertyInfo> properties = GetPropertiesForType<T>();
IDictionary<TKey, T> result = new Dictionary<TKey, T>();
Dictionary<string, int> propDict = GetPropertyDictionary(properties, table);
foreach (var row in table.Rows)
{
var item = CreateItemFromRow<T>((DataRow)row, properties, propDict);
TKey pk = getKey((DataRow)row);
result.Add(pk,item);
}
return result;
}
可以这样称呼:
IDictionary<Int16,DBClient> Clients = sql.GetDataTable("SELECT * FROM Clients").ToDictionary<Int16,DBClient>(r => r.Field<Int16>("PrimaryKeyField"));
查看Petapoco它允许您从数据库检索CLR对象和列表。它没有太多开销。
这可以通过反射来实现查看此链接可能会帮助您在这篇文章中,我试图将数据集转换为列表