如何从IQueryable.GroupBy中选择最新日期?

时间:2013-04-29 16:12:06

标签: c# linq

我从here

获得了以下代码
    var distinctAllEvaluationLicenses = allEvaluationLicenses.GroupBy((License => 
License.dateCreated)).Select(License => License.First());

如何选择最新的'dateCreated'而不是First??

2 个答案:

答案 0 :(得分:3)

如果你想要的只是最大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();

答案 1 :(得分:1)

您可以使用Max来获取最大的序列。

var distinctAllEvaluationLicenses = allEvaluationLicenses.GroupBy(License => 
License.dateCreated)
    .Max(group => group.Key);

那就是说,在这个特定的背景下,似乎没有任何理由进行分组:

var distinctAllEvaluationLicenses = allEvaluationLicenses
    .Max(License=> License.dateCreated)