LINQ 查询中的 Max() [英] Max() in LINQ Query
问题描述
我有一个 DataType 为 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屋!