我正在尝试从我的 DataTable 创建字典。目前,我首先创建一个 IList,然后循环遍历 List 并将它们添加到字典中,根据具体情况分别指定列表中结果对象的主键属性。
我想知道这是否可以使用泛型来完成。
我目前有以下代码,无法编译或工作:
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>();
我假设在某处我需要将主键属性名称传递给此函数。如果失败,我可以安全地假设我的数据表中的第一列包含主键(尽管假设它始终是一个 int(它可能是一个 short 或字节)是不安全的)。
我也明白这可以很容易地使用 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 扩展方法。
如果您有任何其他问题,请随时提出。
关于c# - 使用泛型和扩展方法将 DataTable 转换为 Dictionary<T1,T2>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9306082/