Consider this code:
var joWork = ((JObject) x).Properties()
.Where(p => p.Value.Type == JTokenType.String).ToList();
I end up with a List<JProperty>
.
Is there a quick way using Linq or a JSON.NET function to convert that List<JProperty>
object to a JObject without building a JObject from scratch in a loop?
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
.Properties()
.Where(p => p.Value.Type == JTokenType.String)
.ToList();
var recreated = new JObject(properties);
Console.WriteLine(recreated);
}
}
Output:
{
"x": "a",
"y": "b"
}
(The z
property is missing because its value isn't a string.)