You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用C# List<>的GroupBy功能按CurrencyCode取最高Id记录?

解决方案

方法一:LINQ GroupBy + 排序取首元素

先按CurrencyCode分组,每组内按Id降序排列后取第一个元素(即Id最大的记录),写法直观易懂:

var result = list.GroupBy(c => c.CurrencyCode)
                 .Select(g => g.OrderByDescending(c => c.Id).First())
                 .ToList();

方法二:LINQ GroupBy + Aggregate(性能更优)

避免排序的额外开销,通过Aggregate遍历组内元素,直接保留Id最大的记录,时间复杂度更低:

var result = list.GroupBy(c => c.CurrencyCode)
                 .Select(g => g.Aggregate((currentMax, next) => next.Id > currentMax.Id ? next : currentMax))
                 .ToList();

方法三:.NET 6+ 专用:GroupBy + MaxBy

.NET 6及以上版本提供了MaxBy方法,可直接获取组内指定字段最大的元素,代码更简洁:

var result = list.GroupBy(c => c.CurrencyCode)
                 .Select(g => g.MaxBy(c => c.Id))
                 .ToList();

按期望格式输出结果

如果需要匹配你给出的输出样式,可使用以下打印代码:

foreach (var currency in result)
{
    Console.WriteLine($"{currency.Id,-3} {currency.CurrencyCode,-10} {currency.BuyRate,-12} {currency.SellRate}");
}

运行后输出:

3  USD          1.121454     1.145748
5  EUR          1.424857     1.564578
6  AUD          2.154857     2.487876

内容的提问来源于stack exchange,提问作者altunu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 15:10:28