Grouping sections of the source, each element is assigned to one group.
You have a good start:
var data = new[] { new { Id = 0, 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 ) );
Follow him:
int soFar = 0; Dictionary<int, int> counts = grouped.ToDictionary(g => g.Key, g => g.Count()); foreach(int key in counts.Keys.OrderByDescending(i => i)) { soFar += counts[key]; counts[key] = soFar; }
Or if you want to do this in a single linq expression:
int soFar = 0; var grouped = data .GroupBy( x => ranges.FirstOrDefault( r => r <= x.Price ) ) .OrderByDescending(g => g.Key) .Select(g => { soFar += g.Count(); return new Tuple<int, int>(g.Key, soFar) });
Amy b
source share