我需要根据标识符以下列方式对FinalPrice进行舍入:
预期舍入的示例:
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中进行此舍入...
答案 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;
}
}