merging two objects in C#

后端 未结 6 1886
無奈伤痛
無奈伤痛 2020-11-29 07:06

I have an object model MyObject with various properties. At one point, I have two instances of these MyObject: instance A and instance B. I\'d like to copy and replace the p

6条回答
  •  时光取名叫无心
    2020-11-29 07:57

    you can use this package:XASoft

    use foo.Merger(bar) method to combine 2 object to a dynamic object

    just like this

    var objA = new { a = 1, b = 2, c = 3 };
    var newObj = objA.Merger(new { a = "Hey", d = 4, e = 5 });
    newObj.e = "There";
    newObj.f = 6;
    Console.WriteLine(JsonConvert.SerializeObject(newObj));
    

    even if object list works fine too!

    private class TestClass
    {
        public int X { get; set; }
        public int Y { get; set; }
    }
    static void Main(string[] args)
    {
        var list = new List {
            new TestClass{ X=1,Y=2},
            new TestClass{ X=3,Y=4}
        };
        Console.WriteLine(JsonConvert.SerializeObject(list.ListMerger(i => new
            { X = "null value", Z = i.X == 1 ? 0 : 1 })));
    }
    

    oops,looks like javascript language...

    btw,source code click here

提交回复
热议问题