I have the following code trying to get values within a dictionary and cant seem to get it working.
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
namespace DemoTests
{
class Program
{
static void Main(string[] args)
{
string jsonString = "{\"Name\":\"Bob Smith\",\"mainTitle\":\"Title1\",\"emailList\":[\"[email protected]\"],\"rowCount\":\"4\",\"emailSubject\":\"Test Email\",\"items\":{\"sheets\":[[{\"ID\": \"4564342\", \"start\": \"08:00\"}]]}}";
JObject jsonObj = JObject.Parse(jsonString);
Dictionary<dynamic, dynamic> results = jsonObj.ToObject<Dictionary<dynamic, dynamic>>();
List<dynamic> subList = results["items"]["sheets"].ToObject<List<dynamic>>();
foreach (dynamic tableEntries in subList)
{
var entryDict = tableEntries[0].ToObject<Dictionary<dynamic, dynamic>>();
for (int k = 0; k < entryDict.Keys.Count; k )
{
String key = entryDict.Keys.ToList()[k];
Console.WriteLine(key);
}
}
}
}
}
I get an error on line String key = entryDict.Keys.ToList()[k];
Exception thrown: 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' in System.Linq.Expressions.dll An unhandled exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Linq.Expressions.dll 'System.Collections.Generic.Dictionary<object,object>.KeyCollection' does not contain a definition for 'ToList'
How can I get it running? Im pretty new to C# so also open to better ways to write my code
CodePudding user response:
The error message tells you that entryDict.Keys has no function ToList() The .Keys is a key collection which uses an enumerator to walk over it. You cannot acccess it like an array/list.
What you want is this:
foreach (var key in results.Keys)
{
Console.WriteLine(key.ToString());
}
CodePudding user response:
create a list using a constructor
List<string> keyList = new List<string>(entryDict.Keys);
for (int k = 0; k < entryDict.Keys.Count; k ){
String key = keysList[k];
Console.WriteLine(key);
}