简体   繁体   中英

System.linq - GroupBy and Max

How do I combine groupBy and max? I want to group by name and get only the latest version. Something like this

Docs.GroupBy(x => x.Name ).Max(x => x.VersionNumber)

Is it possible?

the following

searchResult.Docs.GroupBy(x => x.PackageName).Select(x => x.Max(x => x.VersionNumber));

returns a

 IEnumerable<int> 

and not

 IEnumerable<Doc> 

Order each group by version number and select first doc only (it will have max version number):

Docs.GroupBy(x => x.Name)
    .Select(g => g.OrderByDescending(x => x.VersionNumber).First())

Your code is not working, because you are selecting value of max version number (which is int) instead of selecting doc which has max version number.

您可以对其进行排序,并获得结果的第一个元素,例如:

searchResult.Docs.GroupBy(x => x.PackageName).OrderByDescending(x => x.Max(x => x.VersionNumber)).FirstOrDefault();

为了获取组的最新元素,查询是:

.GroupBy(x=>x.Name).Select(y=>y.OrderbyDescending(z=>z.Version).FirstorDefault());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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