无法将DataTable转换为Dictionary <int,int>

Dan*_*ell 2 c# linq

我无法让这段代码工作.

DataTable dt = DataManager.GetSectionIdByEmail(test2PortalConnectionString, email);

Dictionary<int,int> clientViewIds = dt.Select(p => new {p.Key, p.Value })
     .AsEnumerable()
     .ToDictionary(kvp => kvp.key as int, kvp => kvp.Value as int);
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:无法将lambda表达式转换为类型'string',因为它不是委托类型

解决方法:我在语句中的AsEnumberable()处于错误的位置,我需要处理数据行.

Dictionary<int,int> clientViewIds = dt.AsEnumerable()
   .Select(dr => new { Key = dr["SectionID"], Value = dr["SectionTypeID"] })
   .ToDictionary(kvp =>(int)kvp.Key, kvp => (int)kvp.Value);
Run Code Online (Sandbox Code Playgroud)

voi*_*hos 7

DataTable不是IEnumerable,所以Select()你实际调用的方法完全不同; 它需要一个字符串.

有一种AsEnumerable()方法可以将其转换DataTableIEnumerable<DataRow>.

但是...... DataRow没有KeyValue属性.所以,我不太清楚你在这里要做什么.您可以使用列访问器来构建字典.

dt.AsEnumerable().Select(dr => new { Key = dr["Key"], Value = dr["Value"] })
    .ToDictionary(kvp => (int)kvp.Key, kvp => (int)kvp.Value);
Run Code Online (Sandbox Code Playgroud)