在linq中得到最后一行 [英] get last row in linq
问题描述
我有1个表有PK是字符串我不能得到最后一行
当我使用按代码desc
I have 1 table that have PK is string I can't get last row
when I use order by code desc
9999 不正确
73858 正确
帮助我请T__T
我来自泰国对不起,如果语言不正确
I'm from Thailand sorry if incorrect language
========================================= ========================
这个问题是由 grek40 非常感谢你
======================================================================= This problem is solve by grek40 Thank you so much
var lastrow = db.table.OrderByDescending(x => x.Code.Length).ThenByDescending( x => x.Code).FirstOrD efault()。Code;
var lastrow = db.table.OrderByDescending(x => x.Code.Length).ThenByDescending(x => x.Code).FirstOrDefault().Code;
推荐答案
由于您的代码
使用字符串算术比较字符串值,其中 9999
更大 73858
,因为它以 9
。你想要的是数字算术,所以首先将你的字符串转换成数字。不幸的是,你不能在EF中使用 int.TryParse
或 Convert.ToInt32
,所以你不会转换你的查询到 IEnumerable
first:
As your Code
-property is a string values are compared using string-arithmetic where 9999
is greater 73858
as it starts with 9
. What you want is number-arithmetic, so convert your strings to numbers first. Unfortunately you can´t use int.TryParse
or Convert.ToInt32
in EF, so you´re stuck on converting your query to an IEnumerable
first:
var query = myQuery.AsEnumerable();
现在您可以转换每个字符串并获取实际的最后一行
Now you can convert every string and get the actual last row
var lastRow = query.OrderByDescending(o => Convert.ToInt32(o.Code)).FirstOrDefault().Code
这意味着你必须将所有的数据都存入内存,以获得最大的价值,当你有很多行时可能是一个问题
This means you´d have to get all the data into memory in order to get the greatest value which might be an issue when you have many rows.
无论如何,其他人已经指出,您应该考虑使用允许此类搜索行为的数据类型。那么你可以从一开始就很容易地避免这些情况。
Anyway as others already pointed out you should consider to use a datatype that allows this kind of search-behaviour. Then you could easily avoid these situations from the very beginning.
这篇关于在linq中得到最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!