简体   繁体   English

将 LINQ 中的 groupby / orderby 查询重写为对象的最佳方法

[英]Best way to rewrite a groupby / orderby query in LINQ to objects

I have some data looking like this:我有一些看起来像这样的数据:

Environment | Time
"1" | 2021/09/01
"2" | 2021/09/02
"1" | 2021/09/03
"3" | 2021/09/01
"1" | 2021/09/03
"1" | 2021/09/04
"3" | 2021/12/01
"2" | 2021/11/02

I need to find the last record (by time) for each environment, so I wrote:我需要找到每个环境的最后一条记录(按时间),所以我写道:

var lastPerEnvironment = data
    .GroupBy(prp => prp.Environment)
    .Select(prp => prp.OrderByDescending(o => o.Time).First());

Of course it works as expected, but I guess there's a simpler way to write it and maybe also more efficient, using a convening library like MoreLINQ for example (or another good to know library?), with some kind of partitioning.当然它可以按预期工作,但我想有一种更简单的方法来编写它,并且可能也更有效,例如使用像 MoreLINQ 这样的召集库(或另一个好知道的库?),并进行某种分区。

I do not need the Linq to SQL translation (but it would be nice if it was also supported by the suggested solution), only Linq to Objects.我不需要 Linq 到 SQL 的翻译(但如果建议的解决方案也支持它会很好),只有 Linq 到对象。

Thanks for suggestions感谢您的建议

You can refer to this SO response : optimize your prp.OrderByDescending(o => o.Time).First() by MaxBy(o => o.Date);您可以参考此 SO 响应:优化您的prp.OrderByDescending(o => o.Time).First() by MaxBy(o => o.Date); (native in.Net 6 but also available in MoreLINQ ) (本机 in.Net 6,但在MoreLINQ中也可用)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM