H.T
H.T

Reputation: 21

Converting int to decimal inside linq statement

I need to get the decimal result of divide tow integers inside linq statement as in the example:

from error in errorslist
select new
{
    res = error.count1 / error.count2
} 

it return result as integer and I cant use Convert.ToDecimal function

Upvotes: 1

Views: 4395

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460018

Integer division results in an int where the fractional part is truncated since it can't be stored in the result type(int). Therefore at least one of both must be a floating point type.

from error in errorslist
select new
{
    res = error.count1 / (double) error.count2
} 

or

from error in errorslist
select new
{
    res = error.count1 / (1.0 * error.count2)
} 

Update If you want the result type to be decimal (because of the title of your question):

from error in errorslist
select new
{
    res = error.count1 / (decimal) error.count2
} 

Upvotes: 4

It'sNotALie.
It'sNotALie.

Reputation: 22794

You need to turn at least one of the values to a decimal:

from error in errorslist
select new
{
    res = error.count1 / (error.count2 + 0m)
}

Upvotes: 0

Related Questions