Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the highest version of a varchar in C#?

Tags:

c#

sql

I am trying to get the latest version of a program in C#. The code below is the only way I have been able to get the code to run in my controller without any errors:

PList = PList.Where(x => x.PSP == LP && x.VERSION == "1.3");

The problem is unless I maintain this code through every new version and correct it in the code to the most current version it will not work correctly.

So I thought that I could use a max function to get the latest version but it is a varchar in the SQL DB and I cannot change it since I do not have the access to change types.

I have tried different ways of doing this like the example below with no luck.

PList = PList.Where(x => x.PSP == LP && x.VERSION.MAX());

Operator '&&' cannot be applied to operands of type 'bool' and 'char'

So how can I get the Max version when I need to know if PSP is equal to LP AND the version is the highest number in the DB? Thank you for your help!

Update

Thank you all for your excellent answers and I can see how some of them might work on their own but none of them have worked with the code I have. I think posting the rest of the code might help make diagnosing the issue a little easier, so here is the rest of the code.

public virtual ActionResult getAjaxP(string TP = null)
{
    if (TP != null)
    {
        var PList = from x in db.iamp_mapping select x;
        PList = PList.Where(x => x.PSP == TP);
        return Json(PList.Select(x => new { x.PS }).Distinct().ToArray(), JsonRequestBehavior.AllowGet);
    }
    return View();
}
like image 621
Goldentp Avatar asked Jan 15 '23 18:01

Goldentp


2 Answers

You could take advantage of the System.Version class.

var maxVersion = PList
    .Select(x => new Version(x.VERSION))
    .Max()
    .ToString();

PList = PList.Where(x => x.PSP == LP && x.VERSION == maxVersion);

This will favor "1.11" over "1.3", for instance.

If this is Linq-to-Sql, it might involve an extra call to the database.

like image 92
Christoffer Lette Avatar answered Jan 18 '23 08:01

Christoffer Lette


It's unfortunate that your version numbers are stored as text. That means that "1.11" is actually earlier than "1.3".

Aside from that, you could use OrderByDescending. For example

var item = PList.Where(x => x.PSP == LP)
                .OrderByDescending(x => x.VERSION)
                .First();

That will get the single item with the highest version number. If there are multiple items matching that version number, it'll get slightly trickier - you'll probably want to group by version and then order by the group key. Basically we'd need more information about what you're trying to achieve.

like image 25
Jon Skeet Avatar answered Jan 18 '23 07:01

Jon Skeet