Упрощение лямбда-выражения, которое использует один и тот же код несколько раз - PullRequest
2 голосов
/ 06 апреля 2020

Есть ли способ, которым я мог бы упростить свое лямбда-выражение:

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() по всему моему выражению. Есть ли способ, которым я могу написать один раз и использовать его снова.

Ответы [ 2 ]

3 голосов
/ 06 апреля 2020

Здесь выражение запроса пригодится, поскольку оно позволяет 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();
0 голосов
/ 06 апреля 2020

Мое предложение заключается в том, что вы добавляете вспомогательные методы в ваш основной класс, например, GetCurrentRent (), GetCurrentPrice (), где вы инкапсулируете .Where(i => i.Iscurrent).FirstOrDefault() logi c. Затем в своем выражении Select вы просто вызываете эти вспомогательные методы. Это значительно очистит этот код, а также сохранит инкапсуляцию вашего 'logi c' в классе.

models = _context.something
    .Where(i => i.Amount > 0)
    .Select(o => new somemodel
    {
        one = (o.property.GetCurrentPrice().Value - o.property.GetCurrentPrice().Value.Price).ToString(),
        two = o.property.GetCurrentPrice().Value.Price,
        three = o.property.GetCurrentPrice().Value.Price.ToPriceStr("£"),
        four = o.property.GetCurrentRent().Rent * 1200 / o.property.GetCurrentRent().Price,
        five = Convert.ToInt64(o.property.GetCurrentPrice().Value) * o.property.amount,
        six = (Convert.ToInt64(o.property.GetCurrentPrice().Value) * o.property.amount).ToPriceStr("£"),
    })
    .Distinct()
    .ToList();

, после чего вы сможете сделать еще один шаг вперед и выбрать только текущую цену и аренду как tuple ', а затем запустите свою логику c над этим:




models = _context.something
    .Where(i => i.Amount > 0)
    .Select(x => new { Amount = x.amount, CurrentPrice = x.GetCurrentPrice(), CurrentRent = x.GetCurrentRent() })
    .Select(o => new somemodel
    {
        one = (o.CurrentPrice.Value - o.CurrentPrice.Value.Price).ToString(),
        two = o.CurrentPrice.Value.Price,
        three = o.CurrentPrice.Value.Price.ToPriceStr("£"),
        four = o.CurrentRent.Rent * 1200 / o.CurrentRent.Price,
        five = Convert.ToInt64(o.CurrentPrice.Value) * o.Amount,
        six = (Convert.ToInt64(o.CurrentPrice.Value) * o.Amount).ToPriceStr("£"),
    })
    .Distinct()
    .ToList();
...