Group by variable integer range using Linq

后端 未结 4 1225
说谎
说谎 2020-11-27 20:40

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

相关标签:
4条回答
  • 2020-11-27 20:56

    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 ) );
    
    0 讨论(0)
  • 2020-11-27 21:00

    Parameterizing the list of range ceilings...

    var ceilings = new[] { 10, 100, 500 };
    var groupings = items.GroupBy(item => ceilings.First(ceiling => ceiling >= item));
    
    0 讨论(0)
  • 2020-11-27 21:00

    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.

    0 讨论(0)
  • 2020-11-27 21:13

    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.

    0 讨论(0)
提交回复
热议问题