简体   繁体   English

C# FirstOrDefault() 即使使用 System.Linq 也不起作用

[英]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. C# 初学者在这里:我只想看到有与当前用户年龄相同的员工的设施。

For some reason FirstOrDefault() has a red line under it saying:出于某种原因, FirstOrDefault()有一条红线,上面写着:

'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? “Facility”不包含“FirstOrDefault”的定义,并且无法找到接受“Facility”类型的第一个参数的可访问扩展方法“FirstOrDefault”(您是否缺少 using 指令或程序集引用?

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.在文件的顶部,我有“使用 System.Linq”,我知道它正在工作,因为没有它,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.您已经在迭代facilities ,我相信Employee属性与Facility类具有一对一的关系,即 Employee 不是列表。

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.这个错误是因为facility.Employee没有实现FirstOrDefault方法。 Probably it's not a List/IEnumerable (or ICollection in general).可能它不是List/IEnumerable (或一般的ICollection )。

You can instead compare by age first, then use FirstOrDefault您可以FirstOrDefault年龄进行比较,然后使用FirstOrDefault

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

Assuming facility.Employee is a list type:假设 factory.Employee 是一个列表类型:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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