从不同变量查询列表的适当方法?
The appropriate way to query List from different variable?
我有一个显示多对多关系的table。从管理员用户那里,我会得到一个在管理员管理下的位置列表。然后从该列表中,我将获得与这些位置相关的用户列表。这是我第一个获取位置列表的工具
var locationManager = db.UserLocation.Where(x => x.userID == userID).ToList();
我不知道下一步该怎么做。假设经理的 id 是编号为 2 的 userID。因此,第一行代码将 return 向我提供一个 userID = 2 的 UserLocation 列表,其中总共包含两个 id 为 1 和 2 的位置。
Database table Image
在我看来,打印出 UserLocation 的下一行代码应该是这样的,但我不想硬编码数字 1 或 2。
var locationRelated = db.UserLocation.Where(x => x.locationId == 1 || x.locationId == 2).ToList();
您可以使用 Enumerable.Contains
来过滤集合:
var locationIds = new []{1, 2};// get ids somehow
var locationRelated = db.UserLocation
.Where(x => locationIds.Contains(x.locationId))
.ToList();
不过好像有错字,万一你再查询db.UserLocation
呢。如果你想获得 Location
(假设它是这样调用的),你可以在一个查询中完成,如果你的实体关系设置正确:
db.UserLocation
.Where(x => x.userID == userID)
.Select(x => x.Location)
.ToList();
我有一个显示多对多关系的table。从管理员用户那里,我会得到一个在管理员管理下的位置列表。然后从该列表中,我将获得与这些位置相关的用户列表。这是我第一个获取位置列表的工具
var locationManager = db.UserLocation.Where(x => x.userID == userID).ToList();
我不知道下一步该怎么做。假设经理的 id 是编号为 2 的 userID。因此,第一行代码将 return 向我提供一个 userID = 2 的 UserLocation 列表,其中总共包含两个 id 为 1 和 2 的位置。 Database table Image
在我看来,打印出 UserLocation 的下一行代码应该是这样的,但我不想硬编码数字 1 或 2。
var locationRelated = db.UserLocation.Where(x => x.locationId == 1 || x.locationId == 2).ToList();
您可以使用 Enumerable.Contains
来过滤集合:
var locationIds = new []{1, 2};// get ids somehow
var locationRelated = db.UserLocation
.Where(x => locationIds.Contains(x.locationId))
.ToList();
不过好像有错字,万一你再查询db.UserLocation
呢。如果你想获得 Location
(假设它是这样调用的),你可以在一个查询中完成,如果你的实体关系设置正确:
db.UserLocation
.Where(x => x.userID == userID)
.Select(x => x.Location)
.ToList();