我有一个简单的方法,其中包含用于计算某些值的查询。
private decimal MyQueryBuilderMethod(List<ThingsViewModel> myThings)
{
return myThings.Where(x => x.Id == 1)
.Select(x => (x.ThisValue * x.That))
.Sum();
}
我的目标是修改该方法以允许我在对象中指定要查询的 x.ThisValue 字段。
如果我要指定查询的 Where 子句,我可能会传递一个谓词,但在这种情况下,我只想更改 x.ThisValue 的值。
private decimal MyQueryBuilderMethod(List<ThingsViewModel> myThings, Func<ThingsViewModel,bool> predicates)
{
return myThings.Where(predicates)
.Select(x => (x.ThisValue * x.That))
.Sum();
}
理想情况下,我想传递如下内容:
MyQueryBuilderMethod(things, x.ThisOtherValue)
最佳答案
以下应该有效:
private decimal MyQueryBuilderMethod(List<ThingsViewModel> myThings,
Func<ThingsViewModel, decimal> thisValue)
{
return myThings.Where(x => x.Id == 1)
.Sum(x => (thisValue(x) * x.That));
}
我还将 Select(...).Sum()
替换为更短但等效的 Sum(...)
。
然后你可以像下面这样调用它:
var result = MyQueryBuilderMethod(myThings, t => t.ThisValue);
关于c# - 我如何使用 Func<> 修改 lambda 的单个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23217373/