Skip to main content
 首页 » 编程设计

c#之如何从 IQueryable.GroupBy 中选择最新日期

2024年02月13日13mayingbao

我从 here 得到了下面的代码

    var distinctAllEvaluationLicenses = allEvaluationLicenses.GroupBy((License =>  
License.dateCreated)).Select(License => License.First()); 

如何选择最新的“创建日期”而不是第一个?

请您参考如下方法:

如果你想要的只是最大 dateCreated,试试这个:

var results = allEvaluationLicenses.Max(x => x.dateCreated); 

如果你想要最大 dateCreated 的许可证,试试这个:

var results = 
    allEvaluationLicenses.GroupBy(x => x.dateCreated) 
                         .OrderByDescending(g => g.Key) 
                         .First(); 

或者在查询语法中:

var results = 
    (from l in allEvaluationLicenses 
     group l by l.dateCreated into g 
     orderby g.Key descending 
     select g) 
    .First();