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?
CodePudding user response:
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();
CodePudding user response:
Assuming facility.Employee is a list type:
var userAge = (int)HttpContext.User.GetAge();
facilities.Where(facility => facility.Employee.Any(e => e.Age.Equals(userAge)));
If not and there is only one employee per facility, then
var userAge = (int)HttpContext.User.GetAge();
facilities.Where(facility => facility.Employee == userAge);
CodePudding user response:
You are already iterating over facilities
and I believe Employee
property has one to one relationship with Facility
class i.e. 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);
CodePudding user response:
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();