简体   繁体   中英

How to assign one object to another in Linq c# without making new

I'm facing an issue in assigning one object to another in Linq to SQL. In this example:

Func<result, result> make = q => new result
{
    Id = q.Id,
    lName = q.lName,
    GroupId = q.GroupId,
    Age = (from tags in q.age where tags.Del == null && tags.lId == q.Id select age).ToEntitySet(),

};

p = (from q in dc.results
        where q.Id == Id.Value
        select make(q)).First();

I am making new and assigning the object, but I don't want to do this, it will cause problem in insertion. I want to assign without making a new object, how is this possible?

Jon Skeet and Marc Gravell have a library called MiscUtil . Inside MiscUtil .Reflection there is a class called PropertyCopy that does exactly what you describe. It only works for .NET 3.5.

It works by running over the public properties of the SourceType, matches them up by name with the public properties of the TargetType, makes sure that each property can be assigned from the source to the target and then creates and caches a copier function for those two types (so you don't do all this reflection every time). I've used it in production code and can vouch for its goodness.

Check this post out for a code example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM