c# - 使用泛型和扩展方法将 DataTable 转换为 Dictionary<T1,T2>

标签 c# generics extension-methods

我正在尝试从我的 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/

相关文章:

c# - 在扩展方法中创建的实例为空

c# - 与在浏览器上运行的 Javascript 共享程序变量值

Java:在不同于泛型类参数的方法返回中使用泛型

language-agnostic - 支持 "partial specialization"的其他语言有哪些?

c# - 什么时候在 CLR 中为泛型的不同实例共享代码?

visual-studio-2010 - 即使不存在 using 语句,Visual Studio 2010 扩展也会向智能感知添加扩展方法

c# - 类库项目中的扩展方法

c# - 如何处理 DALC 中的非必填文件上传字段?

c# - 我们如何在 FluentMigrator 中重命名表的主键?

c# - 如何使用 Entity Framework Core 运行迁移 SQL 脚本