DefaultIfEmpty 仍然抛出异常序列不包含匹配元素

DefaultIfEmpty Still Throwing Exception Sequence Contains No Matching Element

我有一个看起来像这样的方法:

public static string MyMethod(string myParameter)
{
    var defaultProperty = new Validation() {IDNumber = "ID Number Not Found", Logon = "ID Number Not Found" };
    try
    {
        return lstLogons.DefaultIfEmpty(defaultProperty).Single(x => x.IDNumber == myParameter).Logon;
    }
    catch (Exception exception)
    {
        throw new ArgumentException(exception.Message, myParameter);
    }
}

测试时,我给 myParameter 一个我知道不存在的值,所以我希望能够为这些类型的情况提供一个默认值。但是,它只是抛出一个异常:

Sequence contains no matching element

我知道它不包含我正在搜索的元素.. 因此 need/want 作为默认值。

我怎样才能使这个工作?

这是因为你在那之后调用Single(),而DefaultIfEmpty()将return集合中只有一个项目并且调用Single()意味着总是会有始终是其中符合您指定的条件但不匹配的项目,您在这里需要什么SingleOrDefault() 如果找不到匹配的项目,它不会抛出异常,相反它会 return null.

I want to return a default

您可以为其创建一个具有默认值的局部变量:

var logon = String.Empty;

var result =  lstLogons.SingleOrDefault(x => x.IDNumber == myParameter);
if(result!=null)
    logon = result.Logon;

return logon;