Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

asp.net mvc - Max() in LINQ Query

I have a Column with DataType as Nvarchar(max) Sample Records:

Advisor_Code
9001
9002
9003
100001
100001
9011

I have tried this Query :

var code = (from a in db.advisor_Registration select a ).Max(a=>a.advisor_Code);

It Returns 9011 but max Number is 100001 . How to fix it

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since one of the tags is 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();

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...