使用LINQ通过范围组[重复](Group by range using linq [duplica

2019-07-05 00:04发布

这个问题已经在这里有一个答案:

  • 由可变整数组范围使用LINQ 4个答案

我们如何使用范围电邮宣传比等于或大于?

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 10-50 -> 3 
price 50-100 -> 1 
price 100-500 -> 2 

所需的输出由比所使用的范围等于或大于分组

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

Answer 1:

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

而另一个选项(如果你有大量的数据,然后分组比枚举每个价格组的所有数据更好):

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


Answer 2:

分组分区源,每个项被分配给一个组。

你有什么是一个好的开始:

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

与跟进:

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声明:

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


文章来源: Group by range using linq [duplicate]