Search code examples
c#linqdefaultifempty

DefaultIfEmpty Still Throwing Exception Sequence Contains No Matching Element


I have a method that looks like this:

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);
    }
}

When testing, I am giving myParameter a value that I know doesn't exist, so I want to be able to give a default value for these types of situations. But, instead it just throws an exception:

Sequence contains no matching element

I know it doesn't contain the element I am searching for.. hence the need/want for a default value.

How can I make this work?


Solution

  • It is because you are calling Single() after that, and DefaultIfEmpty() will return collection with just one item in it and calling Single() means that there will always be always one item in it with the criteria you specified and it didn't matched, what you need hereSingleOrDefault() which will not throw exception if no matching item found, insead it will return null.

    I want to return a default

    you can create a local variable for that with default value:

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