Jenny
Jenny

Reputation:

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?

Upvotes: 15

Views: 9203

Answers (4)

jpbochi
jpbochi

Reputation: 4406

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 ) );

Upvotes: 6

Av Pinzur
Av Pinzur

Reputation: 2228

Parameterizing the list of range ceilings...

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

Upvotes: 35

Robban
Robban

Reputation: 6802

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.

Upvotes: -1

Marc Gravell
Marc Gravell

Reputation: 1062590

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.

Upvotes: 1

Related Questions