我有一個用戶擁有的角色串列
List<Role> userRoles; // this is a list of roles
然后我有檔案夾,這些檔案夾具有一個或多個關聯角色,并且可以通過 Folders.Roles 訪問。
我想回傳與檔案夾中的欄位匹配的檔案夾串列,并且在 userRoles 串列中的子角色串列中也有一個角色。
我基本上可以使用一些 foreach 陳述句來做我想做的事情......
bool hasRole = false;
List<Folder> folders2 = _customerPortalDbContext.Folders.Where(f => f.ParentFolderId == Guid.Empty).ToList();
foreach(Folder f in folders2)
{
foreach (Role role in f.Roles)
{
if( roles.Any(r => r.Id == role.Id)) hasRole = true;
}
}
但我覺得我過去曾使用一些聰明的 Linq 代碼看到或做過類似的事情,所以希望這可能嗎?就像是
IQueryable<Folder> folders = _customerPortalDbContext.Folders.Where(f => f.FolderType == "FolderType")
&& f.Roles.RoleId.<<Compare to roles in List of roles>>);
uj5u.com熱心網友回復:
假設你有這樣的課程:
class Folder
{
public Guid ParentFolderId { get; set; }
public List<Role> Roles { get; set; }
}
class Role
{
public int Id { get; set; }
}
你的兩個串列:
List<Folder> folders2
List<Role> userRoles = new List<Role>();
我想,你可以嘗試這樣的事情:
bool hasRole = folders2
.Where(f=>f.ParentFolderId == Guid.Empty) // only gets folders with no parent
.SelectMany(f => f.Roles) // gets all roles from all folders
.Any(r => userRoles.Any(ur => ur.Id == r.Id)); // checks if userRoles contains a role with the same Id
如果您覆寫 Role 類中的 Equals 方法,我認為您也可以使用 Contains 而不是 Any 。這可以提高可讀性,但您需要小心,因為它會在每次比較時覆寫它。
uj5u.com熱心網友回復:
獲取 ID 串列并使用Contains:
idList = userRoles.Select(r => r.Id).ToList();
IQueryable<Folder> folders = _customerPortalDbContext.Folders
.Where(f => f.FolderType == "FolderType"
&& f.Roles.Any(r => idList.Contains(r.RoleId)));
Contains將轉換為IS INSQL 運算式,使用您的 ID 串列作為一組常量值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/393770.html
