哪个linq用于在当前集合中的集合中进行集合搜索

时间:2022-07-20 19:03:29

in my database I have Table Courses, each course contains List of Faculties.

在我的数据库中,我有表课程,每个课程包含学院列表。

With LINQ I need to get all courses that have a faculty with specified faculty id.

使用LINQ,我需要获得所有具有指定教师ID的教师的课程。

I am trying to do something like that:

我想做那样的事情:

        var courses = dc.Courses.Include("ClassTimes").Where(course => course.Facultys.Where(fac => fac.Id == currentFacultyId));

but it doesn't work... I am pretty sure there should be another LINQ api that created for this purpose, I just need someone to point me.

但它不起作用......我很确定应该有另一个为此目的创建的LINQ api,我只需要有人指点我。

Thank you

谢谢

2 个解决方案

#1


3  

You can use .Any() to achieve that :

您可以使用.Any()来实现:

var courses = dc.Courses
                .Include("ClassTimes")
                .Where(course => course.Facultys.Any(fac => fac.Id == currentFacultyId));

#2


1  

Use .Contains():

使用.Contains():

var courses = dc.Courses.Include("ClassTimes").Where(course => course.Facultys.Contains(fac => fac.Id == currentFacultyId));

Explanation:

说明:

Contains will solve this problem, since the Where expression expects to return a boolean answer for every item in the collection.

Contains将解决这个问题,因为Where表达式希望为集合中的每个项返回一个布尔答案。

Where - return items that match the given condition.

Where - 返回符合给定条件的项目。

Contains - returns boolean whether the collection contains an item that matches the given condition.

Contains - 返回boolean集合是否包含与给定条件匹配的项目。

#1


3  

You can use .Any() to achieve that :

您可以使用.Any()来实现:

var courses = dc.Courses
                .Include("ClassTimes")
                .Where(course => course.Facultys.Any(fac => fac.Id == currentFacultyId));

#2


1  

Use .Contains():

使用.Contains():

var courses = dc.Courses.Include("ClassTimes").Where(course => course.Facultys.Contains(fac => fac.Id == currentFacultyId));

Explanation:

说明:

Contains will solve this problem, since the Where expression expects to return a boolean answer for every item in the collection.

Contains将解决这个问题,因为Where表达式希望为集合中的每个项返回一个布尔答案。

Where - return items that match the given condition.

Where - 返回符合给定条件的项目。

Contains - returns boolean whether the collection contains an item that matches the given condition.

Contains - 返回boolean集合是否包含与给定条件匹配的项目。