1

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?

Gary
  • 253
  • 3
  • 4
  • 11
  • http://stackoverflow.com/questions/13828216/group-by-range-using-linq – Nard Dog Apr 11 '17 at 18:18
  • What about giving the class a `GetGroup()` method and group by that value? If the grouping logic can be defined by class, that is. – ChriPf Apr 11 '17 at 18:20
  • Group ranges are incorrect as they overlap, where does $10 comes in 0-10 or 10-20, you need to create exclusive ranges – Mrinal Kamboj Apr 11 '17 at 19:01

2 Answers2

5

This should work : var groups = orders.GroupBy(order => order.Price - order.Price % 10);

Toto
  • 7,491
  • 18
  • 50
  • 72
  • 1
    Due to the idiosyncrasies of how doubles work and the fact that a `GroupBy` does a `.Equals(` comparison to make its groups I would be careful of this answer. When dealing with larger numbers you may end up with groups with a fraction of a cent assigned to them. – Scott Chamberlain Apr 11 '17 at 18:23
  • Meh, I ran some tests, I could not get it to fail on any number between `0` and `Int32.MaxValue`. I also tried `Int64.MaxValue`, `Int64.MaxValue-1`, `Double.MaxValue`, and `Double.MaxValue - 1.2` and those did not fail either. I think for most reasonable uses this method is fine to do. – Scott Chamberlain Apr 11 '17 at 18:43
  • Why does $10 belongs to 0-10 not 10-20 ? – Mrinal Kamboj Apr 12 '17 at 01:28
4

Use integer arithmetic and GroupBy, for example:

orders.GroupBy(o => (int)o.Price / 10)

driis
  • 161,458
  • 45
  • 265
  • 341