DeniseMeander
DeniseMeander

Reputation: 838

JObject toDictionary() using lambda only gives me values not the keys

I'm trying to convert a JSON list of key value pairs stored in a JObject to a C# dictionary. I came really close but got stuck.

Newtonsoft.Json.Linq.JObject jContainer = new Newtonsoft.Json.Linq.JObject();
Newtonsoft.Json.Linq.JObject jCodes = new Newtonsoft.Json.Linq.JObject();

jCodes.Add("UJ2W", "12345");
jCodes.Add("T62Q", "12346");
jCodes.Add("8I4D", "12347");
jCodes.Add("T45G", "12348");
jCodes.Add("Q91B", "12349");

jContainer.Add("codes", jCodes);
jContainer.Add("company", "Some Company");
jContainer.Add("log", "URL to logo");

Dictionary<string, string> dCodeTranslation = jContainer["codes"]
    .ToDictionary(k => (string)k, v => (string)v);

No matter which lambda code I use (I tried o, v and some other stuff) it keeps returning this dictionary:

12345 - 12345
12346 - 12346
12347 - 12347
12348 - 12348
12349 - 12349

instead of

UJ2W - 12345
T62Q - 12346
8I4D - 12347
T45G - 12348
Q91B - 12349

Upvotes: 1

Views: 405

Answers (1)

Gilad Green
Gilad Green

Reputation: 37299

Casting the items to JProperty enables you to retrieve their Name and Value:

var dCodeTranslation = jContainer["codes"].ToDictionary(
    k => { return ((JProperty)k).Name; }, 
    v => { return (string)((JProperty)v).Value; });

//output:
//UJ2W - 12345
//T62Q - 12346
//8I4D - 12347
//T45G - 12348
//Q91B - 12349

However you might want to think about ToLookup in case you might have several values for each key

Upvotes: 2

Related Questions