同事让我写一个一行来替换下面的方法:
public static bool IsResourceAvailableToUser(IEnumerable<string> resourceRoles, IEnumerable<string> userRoles)
{
foreach (var userRole in userRoles)
foreach (var resourceRole in resourceRoles)
if (resourceRole == userRole)
return true;
return false;
}
Resharper 和我想到了这个:
public static bool IsResourceAvailableToUser(IEnumerable<string> resourceRoles, IEnumerable<string> userRoles)
{
return userRoles.Where(resourceRoles.Contains).Count() > 0;
}
有没有更好的办法?
最佳答案
鉴于 LINQ,是的:
return userRoles.Intersect(resourceRoles).Any();
请注意,除了使用 Intersect
将其转换为 O(m) + O(n) 而不是 O(m * n) 之外,使用 Any
更合适比使用 Count() > 0
更高效 - 一旦找到第一个匹配项,您就会知道答案。
关于c# - 检查列表中的任何项目是否与另一个列表中的任何项目匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2508087/