【问题标题】:Convert list<object> list to dictionary from linq to sql query results c#将 list<object> 列表转换为字典,从 linq 到 sql 查询结果 c#
【发布时间】:2017-08-18 13:28:18
【问题描述】:

我正在尝试将 ling 的结果转换为 sql 选择结果到字典。

什么时候做:

var dict = new Dictionary<string, string>();
var encodedContent = new FormUrlEncodedContent(dict);

id 可以毫无问题地接受字典。

当我这样做时:

var dict = leads
    .Select((s, i) => new { s, i })
    .ToDictionary(x => x.i, x => x.s)
    .GetEnumerator();

var encodedContent = new FormUrlEncodedContent(dict);

我收到此错误:

严重性代码描述项目文件行抑制状态 错误 CS1503 参数 1:无法从 System.Collections.Generic.Dictionary&lt;int,PostLeadsToClient.Models.EducatorLead&gt;.EnumeratorSystem.Collections.Generic.IEnumerable&lt;System.Collections.Generic.KeyValuePair&lt;string, string&gt;&gt; PostLeadsT​​oClient C:\RGI Projects\PostLeadsT​​oClient\PostLeadsT​​oClient\Program.cs 159 活动

我一生都无法弄清楚我做错了什么。

我把查询的结果转换错了吗?

【问题讨论】:

  • 不要打电话给GetEnumerator
  • 另外,如果FormUrlEncodedContent 采用Dictionary&lt;string, string&gt;,您需要在索引和EducatorLead 对象上调用ToString(或以某种方式将它们转换为string

标签: c# asp.net-mvc http-post


【解决方案1】:

从查询中删除 GetEnumerator(),因为您需要字典。

错误消息告诉您,您传递了一个枚举器,但所需的类型是 IEnumerable&lt;KeyValuePair&lt;string, string&gt;&gt;,这是 Dictionary&lt;string, string&gt; 实现的。

所以这应该可以工作(注意我使用x.i.ToString(),因为iint):

var dict = leads
    .Select((s, i) => new { s, i })
    .ToDictionary(x => x.i.ToString(), x => x.s); // note the ToString

var encodedContent = new FormUrlEncodedContent(dict);

【讨论】:

  • 没关系。一旦我做了 .ToString() ,它的工作都很棒。谢谢蒂姆,你为我节省了很多时间。
猜你喜欢
  • 2010-10-31
  • 1970-01-01
  • 1970-01-01
  • 2012-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-22
相关资源
最近更新 更多