[英]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. 我在将Linq中的一个对象分配给另一个对象时遇到了问题。 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 . 乔恩·斯凯特(Jon Skeet)和马克·格雷夫(Marc Gravell)拥有一个名为MiscUtil的库。 Inside
MiscUtil
.Reflection there is a class called PropertyCopy
that does exactly what you describe. 在
MiscUtil
.Reflection内部,有一个名为PropertyCopy
的类,它完全按照您的描述进行操作。 It only works for .NET 3.5. 它仅适用于.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). 它通过运行SourceType的公共属性来工作,通过名称将它们与TargetType的公共属性进行匹配,确保可以将每个属性从源分配给目标,然后为这两个属性创建并缓存复印机功能类型(因此您不必每次都进行所有反射)。 I've used it in production code and can vouch for its goodness.
我已经在生产代码中使用了它,并且可以保证它的优点。
Check this post out for a code example . 查看此帖子以获取代码示例 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.