© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
17 replies
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);
   }
 }
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.'
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
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ Reading from a JSON file
C#CC# / help
3y ago
❔ How can I read data from file called lang.json
C#CC# / help
3y ago
Unable to Populate XAML TextBlock with Data from JSON File
C#CC# / help
3y ago
Null reffrence from Json file(monogame)
C#CC# / help
15mo ago