关于 c#:Group by range using linq

Group by range using linq

本问题已经有最佳答案,请猛点这里访问。

我们如何使用分组范围等于或大于?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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 ) );

grouped ouput is
price 1050 -> 3
price 50100 -> 1
price 100500 -> 2

需要的输出按等于或大于使用的范围分组

1
2
3
4
price >= 10 -> 6
price >= 50 -> 4
price >= 100 -> 3
price >= 500 -> 1


1
2
3
var grouped = ranges.Select(r => new {
            Price = r,
            Count = data.Where(x => x.Price >= r).Count() });

还有另一个选择(如果你有大量数据,那么分组比枚举每个价格组的所有数据要好):

1
2
3
4
5
6
7
8
9
var priceGroups = data.GroupBy(x => ranges.FirstOrDefault(r => r > x.Price))
                      .Select(g => new { Price = g.Key, Count = g.Count() })
                      .ToList();

var grouped = ranges.Select(r => new
{
    Price = r,
    Count = priceGroups.Where(g => g.Price > r || g.Price == 0).Sum(g => g.Count)
});


分组对源进行分区,每个项目分配到一个组。

你所拥有的是一个好的开始:

1
2
3
4
5
6
7
8
9
10
11
12
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 ) );

跟进:

1
2
3
4
5
6
7
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;
}

或者如果你想在一个 linq 语句中做到这一点:

1
2
3
4
5
6
7
8
9
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)
  });

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/269600.html

(0)
上一篇 2022年6月22日
下一篇 2022年6月22日

相关推荐

发表回复

登录后才能评论