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 查询,以便在数量小于总量的 1% 时将"名称"分组为"其他"。
所以查询的结果应该是这样的
Apple 56
Banana 23
Others 2 -- ( peach's quantity less than than 1% + Mango Quantity less than 1%)
嗯,听起来首先你需要知道总量。这很简单:
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() });
您可以组合"分组和选择"操作,但我个人认为上述操作更容易阅读。