Using System.Text.Json.Nodes, I have this system for searching for countries, where I store the search term along with the data, so I don't have to make repetitive API calls for the same search:
if (countryCache.TryGetValue(countryCache.Keys.FirstOrDefault(textInput.Contains) ?? string.Empty, out JsonArray? countryData) == false) {
UpdateScreen("Loading country data...");
countryData = GetLocationData($"countries?sort=name&filter%5Bname%5D={textInput}");
countryCache.Add(textInput, countryData);
} else {
countryData = [.. countryData.Where(c => c!["attributes"]!["name"]!.ToString().Contains(textInput))];
}
The line with countryData.Where() keeps throwing the exception 'The node already has a parent.' and I don't understand why. As I understand, the collection expression should just create a copy of the collection, not reference or reparent it. Is there something I'm missing about the behaviour of JsonArrays?
I also tried initialising the JsonArray before the if statement, assigning the result of the collection expression to a separate JsonArray, and using DeepClone(), with the same results. Thanks.