Robert_Junior
Robert_Junior

Reputation: 1123

Grouping a range using linq

I have list of objects (ID,Price,SalesID )
How can I group this list based on a range of Price values?

Say from 0-10,10-20,>20

I want ouput as a list of groups

0-9 -> object1,object2  
10-20 -> object3,object5,object7
>20   -> object8,object10,object11..

Upvotes: 0

Views: 115

Answers (4)

Gert Arnold
Gert Arnold

Reputation: 109079

I would make groups that contain the range names:

var result = prices.GroupBy(x => x.Price < 10 ? "0-10" 
                                              : x.Price < 20 ? "10-20" : ">20")
                   .Select(g => new { g.Key, g }

(assuming that < 0 does not exist)

Upvotes: 1

StevieB
StevieB

Reputation: 1000

This will group them in ranges of >20, 10-20, <10 (i.e. 0-9 as price can't be less than 0 I assume).

objects.GroupBy(x => x.Price > 20 ? 2 : x.Price >= 10 ? 1 : 0)

Upvotes: 3

Victor Mukherjee
Victor Mukherjee

Reputation: 11025

This should work:

objects.GroupBy(o=>o.Price>=20?2:(int)(o.Price/10))

Upvotes: 0

Mauro Cerutti
Mauro Cerutti

Reputation: 684

You can do something like this:

Define an enum to represent you ranges:

public enum PriceRange {
   LessThanTen,
   TenToTwenty,
   MoreThanTwenty
}

Then define a method similar to the following somewhere:

private static PriceRange ExtractRange(MyClass o) {
    if (o.Price < 10)
        return PriceRange.LessThanTen;
    else if (o.Price <= 20)
        return PriceRange.TenToTwenty;
    else
        return PriceRange.MoreThanTwenty;
}

the you can do something like:

var groups = myObjects.GroupBy(m => ExtractRange(m));

You can output like this:

foreach( var g in grp ) {
        Console.WriteLine("{0} -> {1}", g.Key, string.Join(",", g.Select(o => o.ToString())));
    }

Assuming that you objects' ToString() outputs something useful to you.

Upvotes: 0

Related Questions