繁体   English   中英

c#仅显示小数点后的数字与linq

[英]c# only show numbers after decimal point with linq

我有一个成功执行的linq查询,其中一个返回的列是十进制类型,用于表示以磅和便士为单位的价格(永远不会有任何负值)

我希望能够将磅和便士去掉我的投影的单独属性,但是当使用诸如的功能时

var result= from j in context.Products

 select
   new{
     Price = t.Price,                                                     
     PricePounds = Math.Truncate(t.Price)
   };

我收到一个不支持Math.truncate的错误,因为它无法转换为商店表达式。 如何从此查询中获取磅值?

如果此后你不需要在数据库中做任何其他事情,最简单的方法就是执行截断客户端:

var query = context.Products
                   .AsEnumerable() // Everything from here is LINQ to Objects
                   .Select(p => new {
                               p.Price,
                               PricePounds = Math.Truncate(p.Price)
                           });

请注意,您可能还需要只投来int -并可能在EF已经得到支持。

编辑:如评论中所述,您可能希望首先执行投影,例如

var query = context.Products
                   .Select(p => new { p.Price, p.SomethingElse })
                   .AsEnumerable() // Everything from here is LINQ to Objects
                   .Select(p => new {
                               p.Price,
                               PricePounds = Math.Truncate(p.Price),
                               p.SomethingElse
                           });

(其中SomethingElse是您感兴趣的另一个属性,例如 - 我怀疑您想要价格。)

当您只需要一些属性时,这将避免获取整个实体。

你可以尝试:

var result= from j in context.Products
select
  new {
       Price = t.Price,                                                     
       PricePounds = EntityFunctions.Truncate(t.Price, 0)
      };

案例是Math.Truncate无法转换为EntityFunctions.Truncate应该在的SQL。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM