linq查询将项目分组

时间:2014-12-11 08:39:05

标签: linq linq-group

var sales = _salesService.GetSales(parameters)

列表类似于

var listSales = new List<SalesData>();
listSales .Add(new SalesData
{
    Name = "Apple",
    Quantity = 1000
});
listSales .Add(new SalesData
{
    Name = "Banana",
    Quantity = 2000
});
listSales .Add(new SalesData
{
    Name = "Peach",
    Quantity = 1
});
listSales .Add(new SalesData
{
    Name = "Mango",
    Quantity = 1
});

我想写一个linq查询,以便我可以对&#39; Name&#39;进行分组。作为&#39;其他&#39;如果数量少于总量的1%。

因此查询的结果应该类似于

Apple  56
Banana 23
Others 2  -- ( peach's quantity less than than 1% + Mango Quantity less than 1%)

1 个答案:

答案 0 :(得分:3)

嗯,听起来首先你需要知道总量。这很容易:

var total = listSales.Sum(entry => entry.Quantity);

然后你需要计算出截止点,即1%:

var cutoff = total / 100;

对于分组和总结,我可能分三步进行:

  • 将原始列表转换为条目为“其他”的序列
  • 按名称分组条目
  • 每组总和

所以总体代码是:

var total = listSales.Sum(entry => entry.Quantity);
// TODO: Work out whether you want the cutoff to be exclusive or not.
var cutoff = total / 100;
var results = listSales.Select(entry => entry.Quantity >= cutoff ?
                                            entry :
                                            new SalesData { 
                                                Name = "Others",
                                                Quantity = entry.Quantity
                                            })
                       .GroupBy(entry => entry.Name, entry => entry.Quantity)
                       .Select(group => new { Name = group.Key,
                                              Total = group.Sum() });

可以结合“分组和选择”操作,但我个人觉得上面的内容更简单。