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?

3
  • stackoverflow.com/questions/13828216/group-by-range-using-linq Commented Apr 11, 2017 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. Commented Apr 11, 2017 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 Commented Apr 11, 2017 at 19:01

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.
Why does $10 belongs to 0-10 not 10-20 ?
4

Use integer arithmetic and GroupBy, for example:

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

3 Comments

C# has a % modulo operator.
@AsadSaeeduddin so? I don't see how the modulo operator would be useful here.
Nevermind, Toto's answer showed how you could use it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.