0

If i have two objects obj1 and obj2 of same class,how can i copy all properties of obj1 to corresponding properties of obj2 using linq?

I have tried the following and it works,but am interested to know how to do it via linq.

Class1 TargetInstance=new Class1();
Class1 SourceInstance=GetObjectFromSomeWhere();
PropertyInfo[] objAllProps = SourceInstance.GetType().GetProperties();

foreach (var prop in objAllProps)
 {
     TargetInstance.GetType().GetProperty(prop.Name)
     .SetValue(TargetInstance,prop.GetValue(SourceInstance, null), null);
 }
nvoigt
  • 75,013
  • 26
  • 93
  • 142
Jatinder Walia
  • 143
  • 1
  • 12
  • `List.ForEach()` isn't LINQ but if you want something that looks like LINQ, there's that. LINQ would make sense for querying property values, but assigning them to another object has nothing to do with LINQ. – 15ee8f99-57ff-4f92-890c-b56153 May 02 '17 at 13:34
  • I have seen examples where the aggregate is applied over an array to do string concatenations and other uses etc,so was wondering if we could apply the same over list as well? – Jatinder Walia May 02 '17 at 13:37
  • Do you want a sort of cloning ? [Deep cloning objects](http://stackoverflow.com/questions/78536/deep-cloning-objects) – Pedro Perez May 02 '17 at 13:38
  • @JatinderWalia Aggregating values to produce a new value is not the same thing as performing a series of assignments on an existing object. What do you want to do with lists? Are you referring to the array of properties? – 15ee8f99-57ff-4f92-890c-b56153 May 02 '17 at 13:43

1 Answers1

0

There is no way to do this via LinQ. Linq is an acronym for Language-Integrated-Query. Not data manipulation. Just query.

There are many ways to do this. You could serialize/deserialize your object. Or use reflection and a loop. Or ready made packages like AutoMapper.

But there is no way to do this with alone or even using it for any purpose other than misusing it for the outer loop.

nvoigt
  • 75,013
  • 26
  • 93
  • 142