Linq FirstOrDefault [英] Linq FirstOrDefault

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

问题描述

我有以下LINQ查询:

I have the following LINQ query:

    Manager mngr = (from tr in DataContext.Manager
                    where tr.Name = "Jones").FirstOrDefault();

如何检查查询是否返回了1条记录 我无法做到.计数以获得计数.

How can I check if the query did return 1 record as I cannot do .Count to get the count.

推荐答案

首先,这不是有效的查询.使用查询语法(from blah in blah ...)时,必须具有select子句.应该更像是:

First of all, that is not a valid query. When you use the query syntax (from blah in blah ...), you must have a select clause. It should be more like:

var manager =
    (from n in DataContext.Manager
    where n.Name == "Jones"
    select n).FirstOrDefault();

要回答您的问题,在查询中调用FirstOrDefault()将返回查询的第一个结果或类型的默认值(在这种情况下,很可能是null).对于您要使用的内容,由于查询可能包含多个结果,因此这不是足够的用途.

To answer your question, calling FirstOrDefault() on your query will return the first result of the query or the default value for the type (most likely null in this case). For what you're going for, this won't be an adequate use since the query may contain more than one result.

如果希望验证查询仅返回单个结果,则应改用SingleOrDefault()方法.它将返回查询生成的一项,如果为空,则返回默认值null;如果有多个项,则返回异常.

If you wish to verify that the query only returns a single result, you should use the SingleOrDefault() method instead. It will return either the one item produced by the query, the default value null if it was empty or throw an exception if there was more than one item.

如果您不想引发异常,将前两个结果放入列表并验证您只有一个会更容易.

If you don't want to throw an exception, it may be easier to just throw the first two results into a list and verify that you only have one.

var managers =
    (from m in DataContext.Manager
    where m.Name == "Jones"
    select m).Take(2).ToList();
if (managers.Count == 1)
{
    // success!
    var manager = managers.First();
    // do something with manager
}
else
{
    // error
}

这篇关于Linq FirstOrDefault的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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