linq to json in csharp

To use LINQ to JSON in C#, you first need to include the Newtonsoft.Json NuGet package. This package is a popular JSON library for .NET and offers support for LINQ to JSON functionality.

Once you have included the package, you can deserialize a JSON string into a JObject using JObject.Parse() method. To perform LINQ queries on the JObject, you can use the LINQ extensions such as Where(), Select(), and OrderBy(). You can also use these extensions to create a new JObject or to modify an existing JObject.

Here's an example of using LINQ to JSON in C# to filter a JSON object based on a condition:

main.cs
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;

public class Program
{
    private static readonly string json = @"{
        'name': 'John Doe',
        'age': 30,
        'address': {
            'street': '123 Main Street',
            'city': 'Anytown',
            'state': 'CA',
            'zip': '12345-6789'
        },
        'phoneNumbers': [
            {
                'type': 'home',
                'number': '555-555-1234'
            },
            {
                'type': 'work',
                'number': '555-555-5678'
            }
        ]
    }";

    public static void Main()
    {
        JObject obj = JObject.Parse(json);

        var result = obj["phoneNumbers"]
            .Where(phone => phone["type"].Value<string>() == "home")
            .Select(phone => phone["number"].Value<string>())
            .FirstOrDefault();

        Console.WriteLine(result); // prints "555-555-1234"
    }
}
945 chars
40 lines

In this example, obj["phoneNumbers"] selects the "phoneNumbers" array from the JObject. The LINQ extension methods Where() and Select() are then used to filter and select the "number" property of the phone that has a "type" of "home". The FirstOrDefault() method is used to return the first phone number that satisfies the condition, or null if there is no such phone number.

gistlibby LogSnag