简体   繁体   中英

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?

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

You are already iterating over facilities and I believe Employee property has one to one relationship with Facility class ie Employee is not a list.

Just below code will work

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

The error is because facility.Employee is not implementing the FirstOrDefault method. Probably it's not a List/IEnumerable (or ICollection in general).

You can instead compare by age first, then use FirstOrDefault

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

Assuming facility.Employee is a list type:

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

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