【发布时间】:2009-07-07 16:43:56
【问题描述】:
我正在解决与 Question 222511 类似的问题区别。以下是部分代码:
// Method A:
// This work good, is fast and returns an un-executed query...
DataContext.LoanNote.Join<LoanNote, Customer, int, LoanNote>(
DataContext.Customers, loanNote => loanNote.PrimaryCustomerNumber, customer => customer.CustomerNumber,
(LoanNote loanNote, Customer customer) => new LoanNote()
{
AccountFeeBillAmount = loanNote.AccountFeeBillAmount,
AccountOpenDate = loanNote.AccountOpenDate,
// This goes on and on...
PrimaryCustomer = customer
});
// Method B:
// This on the other hand is a lot slower and I am not sure why...
var resultSelector = BuildJoinResultSelector<LoanNote, Customer, LoanNote("PrimaryCustomer").Compile();
DataContext.LoanNote.Join<LoanNote, Customer, int, LoanNote>(
DataContext.Customers, loanNote => loanNote.PrimaryCustomerNumber, customer => customer.CustomerNumber, resultSelector);
// The build MemberInitExpression method...
private static Expression<Func<TOuter, TInner, TResult>> BuildJoinResultSelector<TOuter, TInner, TResult>(string propertyName) where TResult : class
{
var result = default(Expression<Func<TOuter, TInner, TResult>>);
var resultType = typeof(TResult);
var outerType = typeof(TOuter);
var innerType = typeof(TInner);
var outer = Expression.Parameter(outerType, "outer");
var inner = Expression.Parameter(innerType, "inner");
var bindings = new List<MemberBinding>();
foreach (var property in resultType.GetProperties())
{
if (property.CanRead == false)
{
continue;
}
else if (property.CanWrite == false)
{
continue;
}
else if (property.Name == propertyName)
{
var condition = Expression.Condition(Expression.Equal(inner, Expression.Constant(null)), Expression.New(innerType), inner);
bindings.Add(Expression.Bind(property, condition));
}
else
{
bindings.Add(Expression.Bind(property, Expression.Property(outer, property)));
}
}
var memberInit = Expression.MemberInit(Expression.New(resultType), bindings);
result = Expression.Lambda<Func<TOuter, TInner, TResult>>(memberInit, outer, inner);
return result;
}
【问题讨论】:
-
您的标题中有错字(执行nce)
-
你能贴出方法A的全部代码吗?
-
这只是 Property Init 的 ex:Balance = loanNote.Balance、APR = loanNote.APR 等...
-
如果你能发布一个完整的程序,那真的很有帮助。我们可以编译和使用的东西。尽可能简单。
标签: c# linq performance lambda