C#C
C#4y ago
Owen

❔ Removing JSON data from JSON File

Hey,
I am attempting to remove JSON data from a text file if required (I'm using it as a local database)
This was my attempt:
Database? db = JsonConvert.DeserializeObject<Database>(File.ReadAllText("Files\\Database.json"));
foreach (var pendingOrder in db.PendingOrders)
 {
   var orderIndex = Program.PendingOrders.FindIndex(o => o.CustomerInfo.UserId == pendingOrder.CustomerInfo.UserId && o.CustomerInfo.ChannelId == pendingOrder.CustomerInfo.ChannelId);
   if (orderIndex < 0)
   {
     db.PendingOrders.Remove(pendingOrder);
   }
 }

Obviously, this doesn't work and I receive this error
System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'

I know this is because I am directly modifying the collection by removing the pending order - so I am hopefully looking for a better way of doing this.
Thanks a lot.
image.png
Was this page helpful?