c# - 简化多次使用相同代码的 lambda 表达式

标签 c# .net-core entity-framework-core

有没有办法可以简化我的 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/

相关文章:

c# - char 对象对应于哪个字符编码(Unicode 版本)集?

c# - 关于多语言 URL 重写

azure - AppInsight 日志错误未显示问题

asp.net - Entity Framework : disable delete globally

c# - 如何在ABP框架中复制SQL的ORDER BY NEWID()?

c# - 使用 XElement 从自定义 XML 反序列化 `Dictionary<string, Tuple<string, List<string>>>`

c# - MySql.Data 通过反射

docker - 安装 dotnet 核心工具 Dockerfile

c# - Razor 类库中的图像

c# - 重新映射表时修改 Entity Framework 表达式