LINQ to Entities - 舍入到最接近的美元,最近的半美元,或者根本没有

时间:2012-02-16 16:47:48

标签: c# linq entity-framework linq-to-entities

我需要根据标识符以下列方式对FinalPrice进行舍入:

  • 0 =完全没有
  • 1 =直至下一个美元
  • 2 =接下来的半美元

预期舍入的示例:

  • ID 0:133.15 => 133.15
  • ID 1:133.15 => 134.00
  • ID 2:133.15 => 133.50

 public IQueryable<MyObj> GetPrices()
    {
        int roundingId = 0; //0 = no rounding. 1 = dollar rounding. 2 = half-dollar rounding.

        var prices = from ps in ObjectContext.Products
        select new MyObj
        {
             FinalPrice = (ps.IsCustomPrice ? ps.CustomPrice : ps.Retail),
        }

        return prices;
    }

public IQueryable<MyObj> GetPrices() { int roundingId = 0; //0 = no rounding. 1 = dollar rounding. 2 = half-dollar rounding. var prices = from ps in ObjectContext.Products select new MyObj { FinalPrice = (ps.IsCustomPrice ? ps.CustomPrice : ps.Retail), } return prices; }

我希望我可以使用自定义函数在LINQ to Entities中进行此舍入...

2 个答案:

答案 0 :(得分:2)

这对你有用。您可以清理它以供自己使用,但基本上您只是使用%模运算符来获取分数和? :三元运算符以选择正确的值

var prices = from ps in ObjectContext.Products
             let cents = ps.Price % 1
             let upToDollar = cents > 0 ? (ps.Price + 1 - cents) : ps.Price
             let upToHalfDollar = cents == 0 ? ps.Price : (cents < 0.5 ? (ps.Price + 0.5 - cents) : (ps.Price + 1 - cents))
             select new
             {
               FinalPrice = roundingId == 0 ? ps.Price : (roundingId == 1 ? upToDollar : upToHalfDollar)
             };

答案 1 :(得分:1)

如果你愿意,你可以全部内联,但说实话,这似乎很难阅读。试试这个:

int roundingId = 0; //0 = no rounding. 1 = dollar rounding. 2 = half-dollar rounding.

    var prices = from ps in ObjectContext.Products
    select new
    {
         FinalPrice = GetPrice((ps.IsCustomPrice ? ps.CustomPrice : ps.Retail), roundingId),
    }

private double GetPrice(double price, int roundingOption)
{
    switch (roundingOption)
    {
        case 0:
        //Do stuff
        break;
        case 1:
        //Do stuff
        break;
        case 2:
        //Do stuff
        break;
    }
}