C# 序列不包含元素错误,但我想检查是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/942545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 03:53:24  来源:igfitidea点击:

Sequence contains no elements error but I want to check for null

c#asp.net-mvclinq

提问by Alex

I have the following problem:

我有以下问题:

public Boolean Exists(String userName)
{
    IRepository<User> = new UserRepository();
    User user = userRepository.First(u => u.Name == userName);

    if (user == null) return false;

    // Exists!
    return true;
}

The problem is now, that I can't check the User object for null. Before I get there, I get an InvalidOperationExceptionsaying "The sequence contains no elements".

现在的问题是,我无法检查用户对象是否为空。在我到达那里之前,我得到一个InvalidOperationException说法“序列不包含任何元素”。

This seems really weird to me, especially as I don't want to establish control flow with exceptions (e.g. encapsulate in try..catch and return true/false in the respective parts).

这对我来说似乎很奇怪,尤其是因为我不想建立带有异常的控制流(例如,封装在 try..catch 中并在相应部分返回 true/false)。

What's going on here? Is this normal or is there something wrong with my respository (hint?!)

这里发生了什么?这是正常的还是我的存储库有问题(提示?!)

By the way, this code works perfectlywhen the element that I'm looking for exists (the User is retrieved etc.). It only doesn't work when there is no match.

顺便说一句,当我要查找的元素存在时(检索用户等),此代码可以完美运行。只有当没有匹配时它才不起作用。

采纳答案by JaredPar

Use FirstOrDefault instead of First. This will return null in the face of an empty collection.

使用 FirstOrDefault 而不是 First。这将在面对空集合时返回 null。

IRepository<User> = new UserRepository();
User user = userRepository.FirstOrDefault(u => u.Name == userName);

回答by Tomas Aschan

Try changing .First()to .FirstOrDefault().

尝试更改.First().FirstOrDefault().

回答by ichiban

Use .FirstOrDefault()to prevent that error

使用.FirstOrDefault()以防止错误