jeffkenn
jeffkenn

Reputation: 201

Convert list<object> list to dictionary from linq to sql query results c#

Im trying to convert the results of a ling to sql select results to a dictionary.

when do this:

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

id accepts the dictionary with no issues.

When i do this:

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

var encodedContent = new FormUrlEncodedContent(dict);

I get this error:

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

I cannot for the live of me figure out what I am doing wrong.

Im i convert the results of the query wrong?

Upvotes: 0

Views: 1167

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460168

Remove GetEnumerator() from the query since you want the dictionary.

The error message tells you that you pass an enumerator but the desired type is an IEnumerable<KeyValuePair<string, string>> which a Dictionary<string, string> implements.

So this should work (note that i use x.i.ToString() because i is an int):

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

Upvotes: 2

Related Questions