你可以编写一个通用的扩展方法来处理许多情况。函数本身的实质只有一行代码。
public static bool AnyItem<T>(this IEnumerable<T> source, IEnumerable<T> other, IEqualityComparer<T> comparer = null)
{
return (comparer == null ? source.Intersect(other) : source.Intersect(other, comparer)).Any();
}
较旧、效率较低的解决方案
public static bool AnyItem<T>(this IEnumerable<T> source, IEnumerable<T> other)
{
return source.Any(s => other.Any(o => EqualityComparer<T>.Default.Equals(s, o)));
}
我认为这也比当前答案更有效率(其实不是)。我需要检查获取EqualityComparer是否昂贵,但我愿意怀疑它。
您还可以扩展此函数以接受一个表达式,该表达式将评估要比较的属性,对于包含对象的可枚举对象。
public static bool AnyItem<T, TResult>(
this IEnumerable<T> source,
IEnumerable<T> other,
Expression<Func<T, TResult>> compareProperty = null)
{
if (compareProperty == null)
{
return source.Any(s => other.Any(o => EqualityComparer<T>.Default.Equals(s, o)));
}
return source.Any(s => other.Any(o =>
EqualityComparer<TResult>.Default.Equals(
s.GetPropertyValue(compareProperty),
o.GetPropertyValue(compareProperty))));
}
public static TValue GetPropertyValue<TTarget, TValue>(
this TTarget target, Expression<Func<TTarget, TValue>> memberLamda)
{
var memberSelectorExpression = memberLamda.Body as MemberExpression;
var property = memberSelectorExpression?.Member as PropertyInfo;
return (TValue)property?.GetValue(target);
}
userRoles
构建哈希集合的摊销复杂度应该为O(m),在哈希集合中查找resourceRoles
中的每个项的复杂度总共应该为O(n)。 - Jon Skeet