我有一个这样的代码:
List<Item> items;
if (maxPrice)
{
items = itemsQuery
.Select(x => new Item()
{
Title = x.Key.title,
Description = x.Key.desc,
Stock = x.Key.stock,
Price = x.Max(y => y.price)
}).ToList();
}
else if (minPrice)
{
items = itemsQuery
.Select(x => new Item()
{
Title = x.Key.title,
Description = x.Key.desc,
Stock = x.Key.stock,
Price = x.Min(y => y.price)
}).ToList();
}
else
{
items = itemsQuery
.Select(x => new Item()
{
Title = x.Key.title,
Description = x.Key.desc,
Stock = x.Key.stock,
Price = x.Average(y => y.price)
}).ToList();
}
字符串
是否可以只更改Price = x.DynamicFunc(...)
行?因为除此之外都是一样的。
我试过:
Price = (x) => {
if (maxPrice) { return x.Max(y => y.price)}
else if (minPrice) { return x.Min(y => y.price)}
else { return x.Average(y => y.price)}
}
型
但这给了我一个错误:
Cannot convert lambda expression to type "decimal" because it is not a delegate type.
型
我怎样才能简化这个过程,使我不必在3个if分支中重复整个选择过程?
1条答案
按热度按时间fwzugrvs1#
模拟代码
如果我没理解错的话。您的代码可能看起来像这样:
字符串
它可以与您的源代码不同,但我认为这不会影响解决方案。
我的解决方案
有了上面的代码,我们就可以用下面的代码实现你的目标:
型
解释
我们声明了
Func<ItemCollection, decimal> getPrice;
,但为每个条件分配了不同的函数。然后我们运行:型
getPrice(x)
应执行相应的函数。可能的输出
型