Search code examples
c#.netreferenceusing

C# FirstOrDefault() not working even with using System.Linq


Beginner to C# here: I want to only see the facilities where there is an employee with the same age as the current user.

For some reason FirstOrDefault() has a red line under it saying:

'Facility' does not contain a definition for 'FirstOrDefault' and no accessible extension method 'FirstOrDefault' accepting a first argument of type 'Facility'could be found (are you missing a using directive or an assembly reference?

Here is the line:

facilities = facilities.Where(facility => facility.Employee.FirstOrDefault().Age == (int)HttpContext.User.GetAge());

At the top of the file, I have "using System.Linq" which I know is working because without it there is an error on Where. So, I am wondering what else could cause this issue?


Solution

  • Try this. First, you need to Filters a sequence of values based on a predicate and then return the first element of a sequence. Read more here

    facilities = facilities.Where(facility => facility.Employee.Age == (int)HttpContext.User.GetAge()).FirstOrDefault();
    

    And this is more readable,

    var userAge = (int)HttpContext.User.GetAge();
    facilities = facilities.Where(facility => facility.Employee.Age == userAge).FirstOrDefault();
    

    Agree with @Metro, You can simply use,

    var userAge = (int)HttpContext.User.GetAge();
    var facility = facilities.FirstOrDefault(facility => facility.Employee.Age == userAge);