简体   繁体   中英

'Sequence contains no elements', happening?

It's a WINDOWSFORM

I have combobox, I use this code for auto textboxvalue but I receive this error

Sequence contains no elements

private void cmbOfficeNumber_SelectedIndexChanged(object sender, EventArgs e)
{
    using (UnitOfWork db = new UnitOfWork())

    if (cmbOfficeNumber.SelectedValue.ToString() != null)
    {
        txtOfficeName.Text = db.OfficeRepository.GetOfficeNamebyNumber(cmbOfficeNumber.Text);

    }
}

And this is my repository code

public string GetOfficeNamebyNumber(string officeNumber)
{
    return db.Office.First(g => g.OfficeNumber == officeNumber).OfficeName;
}

EDIT: When using

return db.Office.FirstOrDefault(g => g.OfficeNumber == officeNumber).OfficeName;

I receive a different error

Object reference not set to an instance of an object

If First() results in

Sequence contains no elements

That means the condition in the lambda expression resulted in no hits. Because First requires you to have atleast one match.

If FirstOrDefault().Property results in

Object reference not set to an instance of an object

It means that the lambda expression resulted in no hits, and it returns a default value of the return type. In the case of a reference object it will be null. You then tried to access a property of null which causes the exception.

Simply put. Your problem is that your comparison is returning no hits.

You need to insert a fail safe for this to not crash

Something like:

public string GetOfficeNamebyNumber(string officeNumber)
{
    var result = db.Office.FirstOrDefault(g => g.OfficeNumber == officeNumber);

    if(result == null)
        return string.Empty;

    return result.OfficeName;
}

This can also be shortend to

public string GetOfficeNamebyNumber(string officeNumber)
{
    var result = db.Office.FirstOrDefault(g => g.OfficeNumber == officeNumber);

    return result?.OfficeName ?? string.Empty;
}

Or even

public string GetOfficeNamebyNumber(string officeNumber)
{
    return db.Office.FirstOrDefault(g => g.OfficeNumber == officeNumber)?.OfficeName ?? string.Empty;
}

I hope this step by step explanation gives you the information you need to solve the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM