C# 组合Lambda表达式
我有这个方法C# 组合Lambda表达式,c#,lambda,C#,Lambda,我有这个方法 public Expression<Func<Auction, bool>> GetUnsetDatesAuctionsExpression() { if (condition) return GetAllUnsetDatesAuctionsExpression(); else return (a =>
public Expression<Func<Auction, bool>> GetUnsetDatesAuctionsExpression()
{
if (condition)
return GetAllUnsetDatesAuctionsExpression();
else
return (a =>
(membershipUser.ProviderUserKey != null) &&
(a.OwnerReference == (Guid)membershipUser.ProviderUserKey) &&
((a.Starts == null) || (a.Ends == null)));
}
}
private Expression<Func<Auction, bool>> GetAllUnsetDatesAuctionsExpression()
{
return (a => (a.Starts == null) || (a.Ends == null));
}
它与私有方法中的表达式体相同
当然,这样做是行不通的,因为你不能,一个布尔和一个表达式
return (a =>
(membershipUser.ProviderUserKey != null) &&
(a.OwnerReference == (Guid)membershipUser.ProviderUserKey) &&
(GetAllUnsetDatesAuctionsExpression));
所以,问题是,如何将对私有方法的调用与
(membershipUser.ProviderUserKey != null) &&
(a.OwnerReference == (Guid)membershipUser.ProviderUserKey)
您不能将其更改为以下表达式:
return (a => (a.Starts == null || a.Ends == null));
您不能将其更改为以下表达式:
return (a => (a.Starts == null || a.Ends == null));
尝试以下方法,我删除了多余的括号:
return a =>
membershipUser.ProviderUserKey != null &&
a.OwnerReference == (Guid)membershipUser.ProviderUserKey &&
GetAllUnsetDatesAuctionsExpression().Compile()(a);
// ---------------------------------^^^^^^^^^^^^^
上面的代码使用方法将getAllunsetDateSactionsPression方法返回的表达式树中描述的lambda表达式编译为可执行代码,并生成表示lambda表达式的委托
编辑:我没有注意到您的公共方法返回的是表达式,而不是值。当然,在您的场景中更好。尝试以下我删除了多余的括号:
return a =>
membershipUser.ProviderUserKey != null &&
a.OwnerReference == (Guid)membershipUser.ProviderUserKey &&
GetAllUnsetDatesAuctionsExpression().Compile()(a);
// ---------------------------------^^^^^^^^^^^^^
上面的代码使用方法将getAllunsetDateSactionsPression方法返回的表达式树中描述的lambda表达式编译为可执行代码,并生成表示lambda表达式的委托
编辑:我没有注意到您的公共方法返回的是表达式,而不是值。当然,在您的场景中会更好。创建一个新表达式作为两者的组合,请参见:
创建一个新表达式作为两者的组合,请参见:
您尝试过GetAllenseTDateSauctionsPression吗?您尝试过GetAllenseTDateSauctionsPression吗?问题是我的公共方法GetUnsetDateSauctionsPression返回一个表达式而不是BinaryExpression。@Sachin-BinaryExpression仍然是一个表达式。问题是我的公共方法GetUnsetDateSauctionsPression返回一个表达式表达式不是BinaryExpression。@Sachin-BinaryExpression仍然是表达式。