2017-08-18 25 views
0

我試圖將ling的結果轉換爲sql選擇結果到字典。轉換列表<object>列表從linq到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); 

我得到這個錯誤:

Severity Code Description Project File Line Suppression State Error CS1503 Argument 1: cannot convert from System.Collections.Generic.Dictionary<int,PostLeadsToClient.Models.EducatorLead>.Enumerator to System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, string>> PostLeadsToClient C:\RGI Projects\PostLeadsToClient\PostLeadsToClient\Program.cs 159 Active

我不能爲我的生活弄清楚什麼我做錯了。

我將查詢結果轉換爲錯誤嗎?

+3

不要叫'GetEnumerator'。 –

+0

此外,如果'FormUrlEncodedContent'需要一個'Dictionary ',你需要在索引和'EducatorLead'對象上調用'ToString'(或者以某種方式將它們轉換爲'string') – juharr

回答

2

從查詢中刪除GetEnumerator(),因爲您需要字典。

錯誤消息告訴您,您傳遞了一個枚舉器,但所需的類型是實現的IEnumerable<KeyValuePair<string, string>>

所以這應該工作(注意,我使用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); 
+0

上面的代碼仍然是給我同樣的錯誤。 – jeffkenn

+0

沒關係。一旦我做了.ToString()它的作品很棒。謝謝Tim,你爲我節省了很多時間。 – jeffkenn