gpt4 book ai didi

c# - 通过对多行求和来排序列表

转载 作者:行者123 更新时间:2023-12-02 08:39:21 25 4
gpt4 key购买 nike

我有这样的类(class):

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();

关于c# - 通过对多行求和来排序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17989964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com