Home > OS >  Getting latest version in a table and putting them into a list
Getting latest version in a table and putting them into a list

Time:10-02

I've been at this for days and i still can't find a linq query that works. can anyone help me with a query on how to get the latest version of a item and put them into a list. The data structure looks like this

name  | version
 john |    1.2.35
 john |    1.3
 karen|    2.0
 sora |    1.1.36

output should be

name  | version
 john |    1.3
 karen|    2.0
 sora |    1.1.36

so far i have this code

var packages = _readOnlyContext.Names.AsEnumerable().Select(x => new Names
            {
                Name = x.Name,
                Version = x.Version.ToString()
            });

CodePudding user response:

Used some part of the code from Jonathan, for the testing purpose.

You can use enter image description here

CodePudding user response:

just use GroupBy and OrderByDescending :

var packages = _readOnlyContext.Names.AsEnumerable()
    .OrderByDescending(o=> o.Version)
    .GroupBy(x=> x.Name)
    .Select(x=>
            new Names
            {
                Name = x.Key,
                Version = x.FirstOrDefault(c=> c.Name == x.Key)?.Version.ToString()                         
            }).ToList();    

CodePudding user response:

try this

var result= _readOnlyContext.Names.GroupBy(l => l.Name)
.Select(g => g.OrderByDescending(c => c.Version).FirstOrDefault())
.ToList();

or if you have a lot of properties, but need only 2

var result= _readOnlyContext.Names
.Select(x =>  new {
        Name = x.Name,
         Version = x.Version.ToString()
        })
.GroupBy(l => l.Name)
.Select(g => g.OrderByDescending(c => c.Version).FirstOrDefault())
.ToList();

CodePudding user response:

You can try this

var result = _readOnlyContext.Names
            .GroupBy(s => s.Name)
            .Select(g => new
            {
                Name = g.Key,
                Version = g.Select(s => s.Version).Max()
            }).ToList();
  • Related