Jazimov Jazimov - 1 year ago 165
C# Question

Convert List<Property> To JObject

Consider this code:

var joWork = ((JObject) x).Properties()
.Where(p => p.Value.Type == JTokenType.String).ToList();

I end up with a

Is there a quick way using Linq or a JSON.NET function to convert that
object to a JObject without building a JObject from scratch in a loop?

Answer Source

Yup, you can just pass the list into the JObject constructor, and Json.NET will do the rest. Here's an example:

using System;
using System.Linq;
using Newtonsoft.Json.Linq;

public class Test
    static void Main()
        JObject original = JObject.Parse("{ \"x\": \"a\", \"y\": \"b\", \"z\": 1 }");
        var properties = original
            .Where(p => p.Value.Type == JTokenType.String)

        var recreated = new JObject(properties);


  "x": "a",
  "y": "b"

(The z property is missing because its value isn't a string.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download