2

我有这样的课:

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?

非常感谢任何可以提供帮助的人。

4

1 回答 1

6
UserDataPoint[] myArray =
    myList.GroupBy(udp => udp.User)
            .OrderByDescending(g => g.Sum(udp => udp.Spend))
            .SelectMany(g => g)
            .ToArray();
于 2013-08-01T09:27:08.067 回答