选择分组结果

时间:2016-04-11 12:54:05

标签: c# linq group-by

我有一个客户列表

public class Client
{
    public string ClientID { get; set; } // Client
    public decimal Amount { get; set; } // Sales $
}

e.g。以下数据

ClientID | Amount
---------+-------
000021354|   200
000021353|   300
000021353|   400
000021352|   100
000021351|   200
000021350|   100

代码:

List<Client> cList = new List<Client>();
cList.Add(new Client() { ClientID = "000021354", Amount = 200 });
cList.Add(new Client() { ClientID = "000021353", Amount = 300 });
cList.Add(new Client() { ClientID = "000021353", Amount = 400 });
cList.Add(new Client() { ClientID = "000021352", Amount = 100 });
cList.Add(new Client() { ClientID = "000021351", Amount = 200 });
cList.Add(new Client() { ClientID = "000021350", Amount = 100 });

我希望它按ClientID分组,Sum按销售额分组。应该选择前3名(销售额最多的客户) - 其余应分组为&#34;其他&#34;

所以结果应该是:

ClientID | Amount
---------+-------
000021353|   700 #1 (300 + 400)
000021354|   200 #2
000021351|   200 #3
others   |   200 // (000021352 + 000021350)

但不知何故,我的分组无效:

var Grouped = cList.GroupBy(x => x.ClientID)
                .OrderByDescending(x => x.Select( y=> y.Amount).Sum())
                .Select(x => x).Take(3); //how to add "others" ?

1 个答案:

答案 0 :(得分:0)

请记住GroupBy将返回分组而不是Client列表。您可以轻松地将分组投影回列表,在本例中使用匿名对象。

var clients = cList.GroupBy(x => x.ClientID)
                     .Select(x => new { ClientID = x.Key, AmountTotal = x.Sum(c => c.Amount) })
                     .OrderByDescending(x => x.AmountTotal);

var topThree = clients.Take(3);
var others = clients.Except(topThree);