tags:

views:

559

answers:

4

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?

Thanks! Jenny

A: 

You could select the ints in different sets with Linq.

Something like:

 var newList = theList.Where(i => i < 30 && i >10);

This would get you all of th eints from a certain interval.

Robban
+2  A: 

Perhaps something like (untested):

item.Price <= 10 ? "A" :
     (item.Price <= 100 ? "B" : (item.Price <= 500 ? "C" : "X"))

(and group by this)

If this is LINQ-to-Objects, you could also do this in a static utility function (GetBand(i) or similar); or with LINQ-to-SQL you could do the same with a scalar-UDF mapped to the data-context.

Marc Gravell
+4  A: 

Parameterizing the list of range ceilings...

var ceilings = new[] { 10, 100, 500 };
var groupings = items.GroupBy(item => ceilings.First(ceiling => ceiling >= item));
Abraham Pinzur
+1 because this is naturally extensible for the most general case, since the list of ceilings can itself be dynamically generated via `Enumerable.Range().Select()`
Pavel Minaev
A: 

How about something like this?

var data = new[] {
    new { Id = 1, Price = 2 },
    new { Id = 1, Price = 10 },
    new { Id = 2, Price = 30 },
    new { Id = 3, Price = 50 },
    new { Id = 4, Price = 120 },
    new { Id = 5, Price = 200 },
    new { Id = 6, Price = 1024 },
};

var ranges = new[] { 10, 50, 100, 500 };

var grouped = data.GroupBy( x => ranges.FirstOrDefault( r => r > x.Price ) );
jpbochi
oops, looks like *Abraham Pinzur* was 4 minutes faster than me...
jpbochi