我知道linq了一下,但是我需要能够有一个由代码填充的列表,并使用linq表达式“迭代”它,以便将它与DB行进行比较。
这是我目前的代码
foreach (IdentityReference group in windowsIdentity.Groups)
{
string groupName = group.Translate(typeof(NTAccount)).ToString();
//Query the db for the role(s) associated with this groupname
var query = from adGroup in AuthDbContext.ADGroups
from adGroupRole in AuthDbContext.ADGroupRoles
where adGroup.Name == groupName
&& adGroup.Id == adGroupRole.ADGroupId
select adGroupRole.Role.Name
;
//Add any found roles as claims to be added to the identity
foreach (string Role in query)
{
claims.Add(new Claim(ClaimTypes.Role, Role));
}
}
但我希望通过生成string[]
(来自windowsIdentity.Groups
)来消除第一个foreach循环,并以某种方式在linq中使用它来比较每个字符串条目(groupname)和where子句。
我想这样做是因为我假设每次运行查询时它都会命中数据库,这意味着如果有50个组,它将命中数据库50次。如果它在一个表达式中,我认为它只会击中DB一次。
执行此操作的Linq查询语法是什么?
答案 0 :(得分:4)
仔细看看:
string[] groupNames = windowsIdentity.Groups.Select(g=> g.Translate(typeof(NTAccount)).ToString()).ToArray();
//Query the db for the role(s) associated with this groupname
var query = from adGroup in AuthDbContext.ADGroups
join adGroupRole in AuthDbContext.ADGroupRoles on adGroup.Id equals adGroupRole.ADGroupId
where groupNames.Contains(adGroup.Name)
select adGroupRole.Role.Name;
//Add any found roles as claims to be added to the identity
foreach (string Role in query)
{
claims.Add(new Claim(ClaimTypes.Role, Role));
}
假设声明是List< Claim>或者某些超类型的索赔,你可以使用以下方法一次性添加:
claims.AddRange(query.Select(r=> new Claim(ClaimTypes.Role, r)));