Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The lists make it tricky... my earlier reply (below) only applies to like-for-like properties (not the lists). I suspect you might just have to write and maintain code:</p> <pre><code> Student foo = new Student { Id = 1, Name = "a", Courses = { new Course { Key = 2}, new Course { Key = 3}, } }; StudentDTO dto = new StudentDTO { Id = foo.Id, Name = foo.Name, }; foreach (var course in foo.Courses) { dto.Courses.Add(new CourseDTO { Key = course.Key }); } </code></pre> <hr> <p>edit; only applies to <strong>shallow</strong> copies - not lists</p> <p>Reflection is an option, but slow. In 3.5 you can build this into a compiled bit of code with <code>Expression</code>. Jon Skeet has a pre-rolled sample of this in <a href="http://www.yoda.arachsys.com/csharp/miscutil/" rel="noreferrer">MiscUtil</a> - just use as:</p> <pre><code>Student source = ... StudentDTO item = PropertyCopy&lt;StudentDTO&gt;.CopyFrom(student); </code></pre> <p>Because this uses a compiled <code>Expression</code> it will vastly out-perform reflection.</p> <p>If you don't have 3.5, then use reflection or ComponentModel. If you use ComponentModel, you can at least use <a href="http://www.codeproject.com/KB/cs/HyperPropertyDescriptor.aspx" rel="noreferrer"><code>HyperDescriptor</code></a> to get it <em>nearly</em> as quick as <code>Expression</code></p> <pre><code>Student source = ... StudentDTO item = new StudentDTO(); PropertyDescriptorCollection sourceProps = TypeDescriptor.GetProperties(student), destProps = TypeDescriptor.GetProperties(item), foreach(PropertyDescriptor prop in sourceProps) { PropertyDescriptor destProp = destProps[prop.Name]; if(destProp != null) destProp.SetValue(item, prop.GetValue(student)); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload