[英]Using a Linq query to select objects where any value of a property matches values from a list
So I am trying to filter the modules object list by userID
of the currently logged in user.所以我试图通过当前登录用户的用户
userID
过滤模块对象列表。 After that I am trying to take the moduleID
of those selected object.之后,我试图获取那些选定对象的
moduleID
。
Using that I want to filter the reports list to only those that contain a moduleID
that matches any of the the previously obtained list of moduleID
.使用它,我想将报告列表过滤为仅包含与之前获得的
moduleID
列表匹配的moduleID
的报告列表。
I'm not that particularly knowledgeable on Linq and this is what I came up with:我对 Linq 并不是特别了解,这就是我想出的:
var name = User.Identity.GetUserName();
//gets the currently logged in user:
ApplicationUser currentUser =
(ApplicationUser)db.Users.Single(x => x.UserName == name);
//gets moduleID's for modules owned by current user:
var modules = (from i in db.Modules
where i.User == currentUser
select i.ModuleID);
var Reports = from u in db.Reports
where u.moduleID == modules
select u;
I'm having problems with the last portion trying to incorporate the contains method into the statement.我在尝试将 contains 方法合并到语句的最后一部分时遇到了问题。
Any help would be appreciated.任何帮助将不胜感激。
You could simplify the multiple queries to one if I'm inferring your table structure correctly:如果我正确推断您的表结构,您可以将多个查询简化为一个:
var name = User.Identity.GetUserName();
var reports = from r in db.Reports
join m in db.Modules on r.moduleID equals m.ModuleID
where m.User.UserName == name
select r;
You can't compare a int
to a IEnumerable<int>
.您不能将
int
与IEnumerable<int>
。 However you can check if the moduleID
is found within the modules
like this :但是,如果你可以检查
moduleID
是内发现的modules
是这样的:
where modules.Contains(u.moduleID)
You're on the right track.你在正确的轨道上。
var Reports = from u in db.Reports
where modules.Contains(u.moduleID)
select u;
Or using lambda:或者使用 lambda:
var reports = db.Reports.Where(u => modules.Contains(u));
You're close.你很接近。 In Linq its a little backwards from standard SQL.
在 Linq 中,它与标准 SQL 有点倒退。 In its case you want to see if the report's module id is contained in the list of modules, so it would look like this:
在这种情况下,您想查看报告的模块 ID 是否包含在模块列表中,因此它看起来像这样:
var Reports = from u in db.Reports
where modules.Contains(u.moduleID)
select u;
Use the navigation properties if you have a one to many relation you could do directly in your Where clause:如果您可以直接在 Where 子句中执行一对多关系,请使用导航属性:
var name = User.Identity.GetUserName();
var Reports = db.Reports.Where(x => x.Module.User.Name == name);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.