有没有办法可以简化我的 lambda 表达式:
models = _context.something
.Where(i => i.Amount > 0)
.Select(o => new somemodel
{
one = (o.property.prices.Where(i => i.IsCurrent == true).FirstOrDefault().Value - o.property.prices.Where(i => i.IsCurrent == true).FirstOrDefault().Price).ToString(),
two = o.property.prices.Where(i => i.IsCurrent == true).FirstOrDefault().Price,
three = o.property.prices.Where(i => i.IsCurrent == true).FirstOrDefault().Price.ToPriceStr("£"),
four = o.property.rents.Where(i => i.IsCurrent == true).FirstOrDefault().Rent * 1200 / o.property.prices.Where(i => i.IsCurrent == true).FirstOrDefault().Price,
five = Convert.ToInt64(o.property.prices.Where(o => o.IsCurrent == true).FirstOrDefault().Value) * o.property.amount,
six = (Convert.ToInt64(o.property.prices.Where(o => o.IsCurrent == true).FirstOrDefault().Value) * o.property.amount).ToPriceStr("£"),
})
.Distinct()
.ToList();
这只是一个示例,真实的示例多次使用相同类型的代码。它真的很容易出错,就好像我改变它一样,我有很多地方可以做。
代码o.property.prices.Where(i => i.IsCurrent == true).FirstOrDefault()
遍布我的表情。有没有一种方法可以让我一次写入并重复使用它。
最佳答案
这就是查询表达式派上用场的地方,因为它允许 let clauses .
models = (from o in _context.something
where o.Amount > 0
let firstCurrentPrice = o.property.prices.Where(i => i.IsCurrent).FirstOrDefault()
select new some model
{
one = (firstCurrentPrice.Value - firstCurrentPrice.Price).ToString(),
two = firstCurrentPrice.Price,
three = firstCurrentPrice.Price.ToPriceStr("£"),
four = o.property.rents.Where(i => i.IsCurrent == true).FirstOrDefault().Rent * 1200 / firstCurrentPrice.Price,
five = Convert.ToInt64(firstCurrentPrice.Value) * o.property.amount,
six = (Convert.ToInt64(firstCurrentPrice.Value) * o.property.amount).ToPriceStr("£"),
})
.Distinct()
.ToList();
关于c# - 简化多次使用相同代码的 lambda 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61057766/