Perform calculation inside select statement in LINQ

前端 未结 5 872
攒了一身酷
攒了一身酷 2021-01-21 02:17

I have a situation where i have to calculate percentage of two values for example

IEnumerable result = 
    from r in renewalLists
    gro         


        
5条回答
  •  无人共我
    2021-01-21 02:41

    When the expression is traslated to SQL by Linq, it truncates values to an integer while the query is executed, so when I use for example:

    select new SomeModel{
        Value = 3/7
    }
    

    it returns 0.

    but, when I use:

    select new SomeModel{
        Value = 3.0 / 7.0
    }
    

    returns the correct value = 0.428...

    So, I think when you use expressions to be used by Linq To Entities, wich must return double or decimal, you should write or cast all values explicitly as double...

    I hope it helps.

提交回复
热议问题