Search code examples
c#linqgroup-by

Group by variable integer range using Linq


I'm trying to group a set of data based on the range of an integer, by the range does not increase at a fixed interval.

e.g. I have

Item ID Price
1          10
2          30
3          50
4          120

I would like to group the items with price 0 - 10, 11 - 100, and 100-500. So that item 1 is in group A, item 2,3, in group B, item 4 in group C.

The closest I can come up is from items group items by (items.price / 10 )

then join the groups together to get the different ranges.

Any ideas?


Solution

  • Parameterizing the list of range ceilings...

    var ceilings = new[] { 10, 100, 500 };
    var groupings = items.GroupBy(item => ceilings.First(ceiling => ceiling >= item));