Reputation: 15138
I have following data:
Name - Mayor Version - Minor Version - Build version
X - 1 - 0 - 0
X - 1 - 1 - 0
X - 2 - 0 - 0
Y - 0 - 2 - 3
Y - 0 - 1 - 1
Z - 4 - 4 - 4
Now I want to get the highest Version Number with Mayor > Minor > Build grouped by name.
So the output here should be:
X - 2 - 0 - 0
Y - 0 - 2 - 3
Z - 4 - 4 - 4
How to do that in linq? I tried to group by Name and then do a sort by Mayor, then by minor then by build and take the first() but I can't figure out the syntax here...
Upvotes: 0
Views: 128
Reputation: 142903
You can use OrderByDescending
followed with chained ThenByDescending
calls in Select
statement after GroupBy
:
class Version
{
public string Name {get;set;}
public int MajorVersion {get;set;}
public int MinorVersion {get;set;}
public int BuildVersion {get;set;}
}
List<Version> versions = ...;
versions
.GroupBy(x => x.Name)
.Select(g => g.OrderByDescending(g => g.MajorVersion)
.ThenByDescending(g => g.MinorVersion)
.ThenByDescending(g => g.BuildVersion)
.First())
.ToList();
Or try leverage default value tuple comparer:
versions
.GroupBy(x => x.Name)
.Select(g => g.OrderByDescending(g => (g.MajorVersion, g.MinorVersion, g.BuildVersion))
.First())
.ToList();
Upvotes: 3