简体   繁体   English

如何在Linq C#中将一个对象分配给另一个对象而不创建新对象

[英]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.

相关问题 如何将一个图表分配给另一C# - How to assign one chart to another C# C#将一种引用类型分配给另一种引用类型,而不引用该对象 - C# assign one reference type to another without it's reference to the object C#如何将从linq返回的对象分配给'this'引用? - C# How to assign an object returned from linq to 'this' reference? 在C#中将不同的对象分配给一个对象 - Assign different object to a one object in C# c# - 如何将对象列表中的值分配给另一个列表 - How to assign values from an object list to another list in c# 如何将C#动态变量属性分配给另一个动态对象? - How to assign C# dynamic variable properties to another dynamic object? C#linq:如何将对象作为新记录提交到数据库 - c# linq: how to submit object to database as a new record 如何在C#中的新请求中使用Linq的SQL对象 - How Use Object of Linq to SQL in new request in C# C#-如何在使另一个对象可见时移动对象 - C# - How to move objects when making another object visible 如何将值从一种形式传递到另一种形式,而无需在C#中创建形式的新实例? - how to pass a values from one form to another form without creating new instance of a form in c#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM