Merging anonymous types

前端 未结 4 466
孤街浪徒
孤街浪徒 2020-12-08 06:47

How can I merge two anonymous types, so that the result contains the properties of both source objects?

var source1 = new
{
    foo = \"foo\",
    bar = \"ba         


        
4条回答
  •  臣服心动
    2020-12-08 07:12

    The following works in .NET 3.5 (and probably 2.0 as well). I modified davehauser's answer.

        public static object MergeJsonData(object item1, object item2)
        {
            if (item1 == null || item2 == null)
                return item1 ?? item2 ?? new object();
    
            var result = new Dictionary();
            foreach (System.Reflection.PropertyInfo fi in item1.GetType().GetProperties().Where(x => x.CanRead))
            {
                var Value = fi.GetValue(item1, null);
                result[fi.Name] = Value;
            }
            foreach (System.Reflection.PropertyInfo fi in item2.GetType().GetProperties().Where(x => x.CanRead))
            {
                var Value = fi.GetValue(item2, null);
                result[fi.Name] = Value;
            }
            return result;
        }
    

提交回复
热议问题