LINQ查询中的Max() [英] Max() in LINQ Query
问题描述
我有一个数据类型为Nvarchar(max)的列 样本记录:
I have a Column with DataType as Nvarchar(max) Sample Records:
Advisor_Code
9001
9002
9003
100001
100001
9011
我已经尝试过该查询:
var code = (from a in db.advisor_Registration select a ).Max(a=>a.advisor_Code);
返回9011,但最大数量为100001. 修复方法
It Returns 9011 but max Number is 100001 . How to fix it
推荐答案
由于标签之一是 entity-framework 我认为它应该可以翻译成SQL.如果您使用例如Convert.ToInt32
在LINQ语句中,将不会成功.
Since one of the tags is entity-framework I assume it should be translatable into SQL. If you use e.g. Convert.ToInt32
in the LINQ statement, this won't succeed.
在不进行转换的情况下从字符串中获取数字"最大值的一种常见方法是先按长度再按字符串排序:
A common way to get the "numeric" max out of strings without conversion is to order by length and then by string:
var max = myquery.OrderByDescending(x => x.Length)
.ThenByDescending (x => x)
.First();
其中,myquery
可以是针对返回字符串的DbSet
的任何查询.当然,如果任何字符串都不是数字,那么结果将毫无意义.
where myquery
could be any query against a DbSet
that returns strings. Of course the results will be meaningless if any of the strings is not numeric.
这篇关于LINQ查询中的Max()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!