2

我无法让这段代码正常工作。

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);

我得到的错误是:无法将 lambda 表达式转换为类型“字符串”,因为它不是委托类型

解决方法:我在语句中的 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);
4

2 回答 2

7

DataTableis not IEnumerable,因此Select()您实际调用的方法完全不同;它需要一个字符串。

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

但是... DataRows 没有KeyandValue属性。所以,我不太确定你想在这里做什么。您可以使用列访问器来构建字典。

dt.AsEnumerable().Select(dr => new { Key = dr["Key"], Value = dr["Value"] })
    .ToDictionary(kvp => (int)kvp.Key, kvp => (int)kvp.Value);
于 2013-06-06T18:08:17.030 回答
0

DataTable不支持使用 lambda 过滤,要么提供查询,要么不提供参数来获取所有行。

然后你可以提取你的数据:

Dictionary<int,int> clientViewIds = dt.Select()
  .Select(r => new { Key = r["A"], Value=r["B"] })
  .ToDictionary(kvp => kvp.Key as int, kvp => kvp.Value as int);
于 2013-06-06T18:09:49.263 回答