簡體   English   中英

從不同變量查詢列表的適當方法?

[英]The appropriate way to query List from different variable?

我有一個顯示多對多關系的表。 從經理用戶那里,我將獲得經理管理下的位置列表。 然后從該列表中,我將獲得與這些位置相關的用戶列表。 這是我第一個獲取位置列表的工具

var locationManager = db.UserLocation.Where(x => x.userID == userID).ToList();

我不知道下一步該做什么。 假設經理的 id 是編號為 2 的用戶 ID。因此,第一行代碼將返回一個包含 userID = 2 的 UserLocation 列表,其中包含 ID 為 1 和 2 的兩個位置。數據庫表圖像

在我看來,打印出 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(); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM