LINQ to JSON in C#
Query the JSON tree itself, before any classes exist.
using Newtonsoft.Json.Linq;
var feed = JArray.Parse("""
[{"name": "auth", "errors": 0}, {"name": "api", "errors": 7},
{"name": "worker", "errors": 2}]
""");
// LINQ works directly on the tokens, before any classes exist
var noisy = feed
.Where(s => (int)s["errors"] > 0)
.OrderByDescending(s => (int)s["errors"])
.Select(s => $"{s["name"]}: {s["errors"]}");
Console.WriteLine(string.Join("\n", noisy));
How it works
JArray.Parseyields tokens LINQ can enumerate.- Casts like
(int)s["errors"]read leaves inside the query. - Filter, order and project without a model class in sight.
Keywords and builtins used here
intstringusingvar
The run, in numbers
- Lines
- 14
- Characters to type
- 405
- Tokens
- 75
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 53 seconds.
Step 3 of 3 in JSON with Newtonsoft, step 3 of 16 in The open ecosystem.