Reputation: 2057
In my program, I created a list of a custom class. This class contains a integer property. I want to divide an other given integer by the sum of these properties in my list - but Sum()
does not seam to work properly in divisions.
I created a short demo for you, it's a simple console application:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sum
{
class Program
{
static void Main(string[] args)
{
List<Class> list = new List<Class>() {
new Class() { Property = 1},
new Class() { Property = 1},
new Class() { Property = 1},
new Class() { Property = 1},
new Class() { Property = 1},
new Class() { Property = 1}
};
Console.WriteLine("Sum: " + list.Sum(x => x.Property));
Console.WriteLine("Division: " + (2 / list.Sum(x => x.Property)));
Console.ReadLine();
}
}
public class Class
{
public int Property { get; set; }
}
}
I know that I could save the sum of the properties in a new variable and use it afterwards for my division. But shouldn't Sum
should work successful in this situation?
Upvotes: 0
Views: 815
Reputation: 75316
Sum
actually work, but result is 0
because you use integer division: int
divides int
=> result will be int
, you should change:
(2.0 / list.Sum(x => x.Property))
It will work
Upvotes: 2
Reputation: 149040
That's because you're using integer division, not floating-point division. Try using 2f
instead to a float
constant:
Console.WriteLine("Division: " + (2f / list.Sum(x => x.Property)));
Or 2d
instead to a double
constant:
Console.WriteLine("Division: " + (2d / list.Sum(x => x.Property)));
Or 2m
instead to a decimal
constant:
Console.WriteLine("Division: " + (2m / list.Sum(x => x.Property)));
Any one will give you the result you're looking for (with only some difference in accuracy)
Upvotes: 2
Reputation: 460208
I assume that you expect the result to be 2 / 6 = 0,33
but integer division always result in an integer (in C#). So at least one number must be a floating point type like double
.
Console.WriteLine("Division: " + (2d / list.Sum(x => x.Property)));
The division rounds the result towards zero, and the absolute value of the result is the largest possible integer that is less than the absolute value of the quotient of the two operands. The result is zero or positive when the two operands have the same sign and zero or negative when the two operands have opposite signs.
http://msdn.microsoft.com/en-us/library/aa691373(v=vs.71).aspx
Upvotes: 2
Reputation:
I think it will write 0 to the output, because of the integer division.
Upvotes: 0
Reputation: 755141
The problem here is you are using integer division which supports whole numbers only. You want instead to do floating point division which supports decimals
Console.WriteLine("Division: " + ((double)2 / list.Sum(x => x.Property)));
Upvotes: 4