LINQ查询中的Max() [英] Max() in LINQ Query

查看:1432
本文介绍了LINQ查询中的Max()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据类型为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

推荐答案

由于标签之一是我认为它应该可以翻译成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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆