LINQ的最后一条记录 [英] last record in LINQ

查看:92
本文介绍了LINQ的最后一条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好

如何使用LINQ方法从数据库中检索最后一条记录?如果LINQ表没有记录,该如何处理错误?

Hi All

How can i retrieve the last record from database using LINQ method? And how a handle the error if the LINQ table has no records?

推荐答案

只需调用如果您认为表格有可能是空的,请使用

If you think there is a chance your table may be empty, use LastOrDefault()[^] instead. This will return null if nothing is found.

var lastItem = yourQuery.LastOrDefault();
if(lastItem == null)
{
    //Table was empty.
}

很显然,如果您的查询实际上未按任何顺序排序,则最后一个"项目可以为任何内容.

Obviously, if your query isn''t actually ordered by anything, then the "last" item could be anything.


最后一条记录:

1.
参见此 [请参见 [
For last record :

1. See This[^] (the answer is below the advertisements at this link, you will have to scroll a lot).

2. See This[^]

To handle the error, if table has no records:

Its just on the top of my head, i cant check it at present, so syntax error may be there:

if(tablename.Records.Count >0) //something like this will do
    {
         //write your code
    }





参见 [ ^ ]


顺便说一句,您通过谷歌搜索可能节省了您和我很多的时间.
(如果我有帮助,请接受回答或投票)

Anurag



OR

See this[^]


BTW, some googling by you may have saved your and mine lots of time.
(Please accept answer or provide votes if I was helpful)

Anurag


数据库在技术上是无序的(OK记录几乎按其进入的顺序出现,但这并不能保证),因此,如果您需要特定的顺序,则必须添加一些执行此操作的方式(身份列(例如,整数代理键上的列),自定义排序列,日期列等).
如果这样做,您只需要linq即可获取包含订购列的最大值"的记录:如何:在数字序列中找到最大值
[ ^ ].
请注意,如果没有记录,就不会有任何错误:除非您调用Single(),否则条目列表将只是空的,在这种情况下,SingleOrDefault()会更好,并检查默认"
DBs are technically unordered (OK records pretty much come out in the order they went in, but this isn''t guaranteed) so if you need a specific order, you must add some way to do this (identity column [e.g. on an integer surrogate key], a custom ordering column, date column etc).
If you do this, you just need the linq to get the record containing the Max value for your ordering column: How to: Find the Maximum Value in a Numeric Sequence
[^].
Note that there should not be any errors if you have no records: the list of entries will merely be empty, unless you call Single(), in which case SingleOrDefault() will be better, and check for "default"


这篇关于LINQ的最后一条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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