我有这样的课程:
public class UserDataPoint
{
public string User { get; set; }
public string Category { get; set; }
public int Spend { get; set; }
public UserDataPoint(string strUser, string strCategory, int intSpend)
{
User = strUser;
Category = strCategory;
Spend = intSpend;
}
}
其中填充了以下数据:
var myList = new List<UserDataPoint>() {
new UserDataPoint("Bob", "Local", 34),
new UserDataPoint("Bob", "National", 16),
new UserDataPoint("Bob", "Mobile", 7),
new UserDataPoint("John", "Local", 18),
new UserDataPoint("Fred", "National", 22),
new UserDataPoint("Fred", "International", 65) };
我想填充一个数组:
UserDataPoint[] myArray;
使用来自myList的数据,但由“用户”排序,其中总计'花费'。因此,根据上面的示例数据,Fred将在列表中排在第一位(22 + 65 = 87),其次是Bob(34 + 16 + 7 = 57),最后是John(18)。
因此我的结果数组将按此顺序填充:
UserDataPoint[] myArray = new UserDataPoint[] {
new UserDataPoint("Fred", "National", 22),
new UserDataPoint("Fred", "International", 65),
new UserDataPoint("Bob", "Local", 34),
new UserDataPoint("Bob", "National", 16),
new UserDataPoint("Bob", "Mobile", 7),
new UserDataPoint("John", "Local", 18) };
如何实现LINQ语句在myList上执行此排序以给我myArray?
非常感谢能够提供帮助的任何人。
答案 0 :(得分:6)
UserDataPoint[] myArray =
myList.GroupBy(udp => udp.User)
.OrderByDescending(g => g.Sum(udp => udp.Spend))
.SelectMany(g => g)
.ToArray();