[英]Linq - Find max value from a nvarchar type column in SQL Server
在我的 SQL 服务器列中,我的值如下所示。
3.2.31
5.6.81
8.0.3521
25
当我尝试使用 LINQ 而不是 25 获得MAX
值时,我得到 8.0.3521。 下面是我的 LINQ 查询。
var maxCode = InventoryDB.Products.where(p => p.Name == "Reva Health").select( m => m.Code).Max();
Code 的列类型是nvarchar
。
这是 C# 中的代码。 假设这些值是字符串:
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);
}
}
}
}
问题是你有一个字符串,而不是一个数字。 这在 SQL 服务器中很难处理。 以下可能就足够了:
select top (1) col
from t
order by try_convert(int, left(col, charindex('.', col) - 1)) desc,
col desc;
这个版本并不完美。 它在第一个周期之前按数字排序,这足以满足您问题中的数据。
您可以尝试以下表达式:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.