I have a json File that I deserialize with Newtonssoft Json.Net like this:
/* Get current config */
dynamic json = JsonConvert.DeserializeObject<Speaker>(
File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "cfg\\speaker.json"));
dynamic jsonDevice = json.DeviceList;
/* Go through the List */
foreach (Tapi tapi in lvTapiSonos.Items)
{
foreach (var line in jsonDevice)
{
foreach (var l in line)
{
/* If not in List already, add it */
if (l.Key != tapi.Name)
{
/* Add to Config */
json.DeviceList.Add(new Dictionary<string, List<Device>>
{
{
tapi.Name,
new List<Device>
{
new Device
{
Volume = "5",
Ip = currentEditIp,
Name = currentEditName
}
}
}
});
}
}
}
}
string output = JsonConvert.SerializeObject(json, Formatting.Indented);
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "cfg\\speaker.json", output);
foreach
foreach (var line in jsonDevice)
jsonDevice
jsonDevice
foreach var line in json.DeviceList
The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop. http://msdn.microsoft.com/en-us/library/ttw7t8t6.aspx
As explained you can use for loop for your usecase. but if you call ToList() or ToArray you can get copy of items which can be use for iterate
dynamic jsonDevice = json.DeviceList.ToList();