将数据表转换为字典C# [英] Transform a DataTable into Dictionary C#

查看:587
本文介绍了将数据表转换为字典C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何将DataTable转换成Dictionary.我做了这样的事情.

I want to know how to transform a DataTable into a Dictionary. I did something like this.

using System.Linq;

internal Dictionary<string,object> GetDict(DataTable dt)
{
    return dt.AsEnumerable()
      .ToDictionary<string, object>(row => row.Field<string>(0),
                                row => row.Field<object>(1));
}

但是我得到了

System.Data.EnumerableRowCollection不包含"ToDictionary"的定义,最佳扩展方法重载"System.Linq.Parallel.Enumerable.ToDictionary(System.Linq.ParallelQuery,System.Func,System.Collections.Generic. IEqualityComrparer)'有一些无效的论点

System.Data.EnumerableRowCollection does not contains a definition for 'ToDictionary' and the best extension method overload 'System.Linq.Parallel.Enumerable.ToDictionary(System.Linq.ParallelQuery, System.Func, System.Collections.Generic.IEqualityComrparer)' has some invalid argumentsch

我该如何解决?

谢谢

推荐答案

通用方法ToDictionary具有3个参数.您留下了一个,所以它不知道该怎么办.如果要指定所有参数,则为<DataRow, string, object>.

The generic method ToDictionary has 3 parameters. You left one off, so it doesn't know what to do. If you want to specify all of the parameters, it would be <DataRow, string, object>.

internal Dictionary<string,object> GetDict(DataTable dt)
{
    return dt.AsEnumerable()
      .ToDictionary<DataRow, string, object>(row => row.Field<string>(0),
                                row => row.Field<object>(1));
}

当然,如果不使用它们,则编译器可以推断类型,因此不会出现错误.

Of course, if you leave them off, the compiler is able to infer the types, so you don't get the error.

这篇关于将数据表转换为字典C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆