merging two objects in C#

后端 未结 6 1885
無奈伤痛
無奈伤痛 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:56

    This is the same as @Bas Answer but for Merging 2 Object lists

    public class Copycontents
    {
        public static void Work(IList targetList, IList sourceList, Func selector)
        {
            var matchingPrimaryKey = targetList.Select(x => selector(x)).ToList();
    
            foreach (var thismatchingPrimaryKey in matchingPrimaryKey)
            {
                CopyValues(targetList.Single(x => selector(x) == thismatchingPrimaryKey),
                    sourceList.Single(x => selector(x) == thismatchingPrimaryKey));
            }
        }
    
        private static void CopyValues(T target, T source)
        {
            Type t = typeof(T);
    
            var properties = t.GetProperties().Where(prop => prop.CanRead && prop.CanWrite);
    
            foreach (var prop in properties)
            {
                var value = prop.GetValue(source, null);
                if (value != null)
                    prop.SetValue(target, value, null);
            }
        }
    }
    

提交回复
热议问题