I am running a LINQ query that is using local "let" variables to calculate a local value to compare against a parameter that is passed into the query.
I have the following query:
Items = from lead in Items
let total = lead.NurtureActions.Count(q => !q.Deleted)
let completed = lead.NurtureActions.Count(nurtureAction => nurtureAction.Completed && !nurtureAction.Deleted)
let percentage = Math.Round((Double)((completed/total)*100),0,MidpointRounding.ToEven)
where
total>0 &&
percentage == progress
select lead;
The part that is really important above is the following line:
let percentage = Math.Round((Double)((completed/total)*100),0,MidpointRounding.ToEven)
As you can see in my query, I am comparing the result of that query with progress
, which is passed into my function.
For example: I might pass in the value 8
, so progress
will have the value 8
. But the calculated percentage
might initially be 8.223
, but I need that to round to 8
.
I believed that I was doing this 开发者_如何学Ccorrectly, but for some reason, something is not working correctly.
Any ideas of what might be throwing the rounding off? I have also tried the AwayFromZero
option for rounding, but that doesn't work either.
Edit For those who requested more information, I am not sure what value it is calculating. I am not experienced with debugging LINQ queries, and wouldn't know where to begin to find out what that value is. I would provide it if I knew how to get it.
Random guess: total
and completed
are int
s, so (completed/total)
results in a truncated value. The truncated value is multiplied by 100 and then converted to double
.
I guess this produces unexpected results in some cases if you expect that (completed/total)
returns a double
.
Fix:
let total = (double)lead.NurtureActions.Count(...)
let completed = (double)lead.NurtureActions.Count(...)
let percentage = Math.Round((completed/total)*100, ...)
精彩评论