通过求和几行对列表进行排序

本文关键字:列表 排序 几行 求和 | 更新日期: 2023-09-27 18:25:50

我有这样的类:

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?

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

通过求和几行对列表进行排序

UserDataPoint[] myArray =
    myList.GroupBy(udp => udp.User)
            .OrderByDescending(g => g.Sum(udp => udp.Spend))
            .SelectMany(g => g)
            .ToArray();