简体   繁体   中英

Linq - Find max value from a nvarchar type column in SQL Server

In my SQL Server column I have values like below.

3.2.31
5.6.81
8.0.3521
25

When I try to get the MAX value using LINQ instead of 25 I am getting 8.0.3521. Below is my LINQ query.

var maxCode = InventoryDB.Products.where(p => p.Name == "Reva Health").select( m => m.Code).Max();

The column type of Code is nvarchar .

Here's the code in C#. Following the assumption those values are strings:

using System;
using System.Collections.Generic;
using System.Linq;

namespace Linq
{
    class Program
    {
        static void Main(string[] args)
        {
            IEnumerable<string> listOfStrings = new List<string>()
            {
                "3.2.31",
                "5.6.81",
                "8.0.3521",
                "25"
            };

            var doubleList = listOfStrings.ToList()
                .Select(y => y.Contains(".") ? 
                    Convert.ToDouble(y.Split(".").FirstOrDefault()) : 
                    Convert.ToDouble(y))
                .OrderByDescending(x => x);

            foreach(var member in doubleList)
            {
                Console.WriteLine(member);
            }
        }
    }
}
  • Note I.ToList() the IEnumerable thinking you might use this code. You want to grab data from your entityframework object prior to making these linq statements so it is not generating unwanted SQL.

The problem is that you have a string, not a number. This is difficult to handle in SQL Server. The following might be good enough:

select top (1) col
from t
order by try_convert(int, left(col, charindex('.', col) - 1)) desc,
         col desc;

This version is not perfect. It orders by number before the first period, which is sufficient for the data in your question.

You can try below expression:

var maxCode = InventoryDB.Products.where(p => p.Name == "Reva Health")
.Select(l => new { 
                  s=Int32.Parse(l.Code.Substring(0,l.Code.IndexOf('.')!=-1?l.Code.IndexOf('.'):l.Code.Length)) 
                  })
.Max(i=>i.s);

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