Search code examples
c#entity-frameworklinqasp.net-core

Sequence contains no elements in LINQ


In the code shown here, I am getting an error in LINQ:

Sequence contains no elements

When the reason column contains data, it is throwing this exception. Please suggest how to handle this exception.

Code:

if (StudentDetails.rows
                  .Where(c => string.IsNullOrEmpty(c.reason) && !c.leave) 
                  .Min(c => c.joiningdate) < DateTime.UtcNow.AddDays(-180))
    return true;

Solution

  • In the code shown here, I am getting an error in LINQ:

    Sequence contains no elements

    Based on your shared code snippet and description I have tried to reproduce your issue and I was able to simulate the error you are getting. Following is the reference for you.

    enter image description here enter image description here

    When the reason column contains data, it is throwing this exception. Please suggest how to handle this exception.

    According to the error message which indicates can happen if all elements in StudentDetails.rows either have a non-null reason or leave is true, resulting in an empty sequence for the Min method to operate on.

    So the way you are trying would always encounter this exception if the condition doesn't meet.

    In order to overcome the exception, you should first check if there are any elements in the filtered sequence before calling Min. You can use the Any method in Linq to ensure that the sequence is not empty.

    Let's say, I have following data set:

    private readonly List<Student> _studentDetails = new List<Student>
    {
        new Student { reason = "Medical", leave = true, joiningdate = new DateTime(2023, 1, 10) },
        new Student { reason = "Personal", leave = true, joiningdate = new DateTime(2022, 2, 15) },
        new Student { reason = "Vacation", leave = true, joiningdate = new DateTime(2021, 3, 20) },
        new Student { reason = "Disciplinary", leave = false, joiningdate = new DateTime(2023, 4, 1) },
        new Student { reason = "Health", leave = true, joiningdate = new DateTime(2021, 5, 30) },
    };
    

    As you can noticed above dataset would faild the condition, in that scenario I would modify the query as following:

    var filteredRows = _studentDetails
        .Where(c => string.IsNullOrEmpty(c.reason) && !c.leave);
    
    if (filteredRows.Any() && filteredRows.Min(c => c.joiningdate) < DateTime.UtcNow.AddDays(-180))
    {
        return Ok(true);
    }
    

    So in filteredRows is first assigned the result of the Where method, filtering the rows based on your conditions. The Any method is then used to check if filteredRows contains any elements. Only if filteredRows is not empty, the Min method is called to find the minimum joiningdate and no exception would thrown anymore.

    Output:

    enter image description here

    enter image description here

    Note: Please refer to this official document, if you need additional details.