CBC_NS
CBC_NS

Reputation: 1957

How can I set the value for all properties with a given name in parent and related sub objects?

I have an object tree that looks something like the following. I want to clone this object, and while doing so, I want to update all properties called Id to 0. Is this doable using newtonsoft?

public class A
{
    public int Id { get; set; }

    public B B { get; set; }
}

public class B
{
    public int Id { get; set; }

    public string SomeProperty { get; set; } 
}

Upvotes: 2

Views: 368

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129777

Sure, you can make a generic helper method using Newtonsoft's LINQ-to-JSON API to do that:

public static T CloneObjectAndResetIdsToZero<T>(T obj)
{
    var jo = JObject.FromObject(obj);
    var idProps = jo.Descendants()
        .OfType<JProperty>()
        .Where(jp => jp.Name == "Id" && jp.Value.Type == JTokenType.Integer);

    foreach (var prop in idProps)
    {
        prop.Value = new JValue(0);
    }
    return jo.ToObject<T>();
}

Working demo here: https://dotnetfiddle.net/AH5fee

Upvotes: 3

Related Questions