Information Technology Reference
In-Depth Information
from srcProp in typeof (TSource).GetProperties(
BindingFlags .Public | BindingFlags .Instance)
where srcProp.CanRead
The let declares a local variable that holds the property of the same name
in the destination type. It may be null, if the destination type does not
have a property of the correct type:
let destProp = typeof (TDest).GetProperty(
srcProp.Name,
BindingFlags .Public | BindingFlags .Instance)
where (destProp != null ) &&
(destProp.CanWrite)
The projection of the query is a sequence of assignment statements that
assigns the property of the destination object to the value of the same
property name in the source object:
select Expression .Assign(
Expression .Property(dest, destProp),
Expression .Property(source, srcProp));
The rest of the method builds the body of the lambda expression. The
Block() method of the Expression class needs all the statements in an array
of Expression. The next step is to create a List<Expression> where you can
add all the statements. The list can be easily converted to an array.
var body = new List < Expression >();
body.Add( Expression .Assign(dest,
Expression .New( typeof (TDest))));
body.AddRange(assignments);
body.Add(dest);
Finally, it's time to build a lambda that returns the destination object and
contains all the statements built so far:
var expr =
Expression .Lambda< Func <TSource, TDest>>(
Expression .Block(
new [] { dest }, // expression parameters
body.ToArray() // body
),
source // lambda expression
);
Search WWH ::




Custom Search