Reputation: 273
I have a console app written in C#. In my app, I have an object defined like this:
public class Order
{
public double Price { get; set; }
public string Description { get; set; }
public int ItemCount { get; set; }
}
I have the Order
objects in a List<Order>
. I need to group these Orders by their Price. But, the groups represent a price range. For example, I want the following groups:
$0 - $10
$10 - $20
$20 - $30
$30 - $40
$40 - $50
$50 - $60
$60 - $70
$70 - $80
$80 - $90
$90 - $100
Originally, I was going to just loop through the List<Order>
, but it seemed clunky. I felt this was a good case for Linq, but I've come up short. My approach isn't working.
Is there a way to group the orders into $10 increments based on the Price
property with LINQ?
Upvotes: 1
Views: 2104
Reputation: 7719
This should work : var groups = orders.GroupBy(order => order.Price - order.Price % 10);
Upvotes: 5
Reputation: 164281
Use integer arithmetic and GroupBy, for example:
orders.GroupBy(o => (int)o.Price / 10)
Upvotes: 4