这取决于你想要什么:
// are there any common values between a and b?
public static bool SharesAnyValueWith<T>(this IEnumerable<T> a, IEnumerable<T> b)
{
return a.Intersect(b).Any();
}
对于不重叠的名单,这将通过迭代和b各一次。对于重叠的列表,这将遍历a,然后遍历b,直到找到第一个重叠元素。
// does a contain all of b? (ignores duplicates)
public static bool ContainsAllFrom<T>(this IEnumerable<T> a, IEnumerable<T> b)
{
return !b.Except(a).Any();
}
这将遍历一次,然后将迭代通过b,停止b中的第一个元素不在a中。
// does a contain all of b? (considers duplicates)
public static bool ContainsAllFrom<T>(this IEnumerable<T> a, IEnumerable<T> b)
{
// get the count of each distinct element in a
var counts = a.GroupBy(t => t).ToDictionary(g => g.Key, g => g.Count());
foreach (var t in b) {
int count;
// if t isn't in a or has too few occurrences return false. Otherwise, reduce
// the count by 1
if (!counts.TryGetValue(t, out count) || count == 0) { return false; }
counts[t] = count - 1;
}
return true;
}
类似地,这将通过一次迭代,然后将至b迭代,b中不处于停止在第一元件上。
定义“份额值”。你的意思是“两个名单中都包含完全相同的人”? –
我相信他的意思是有一些共同的价值(=相交),你可以从所需的方法'Bool DoIntersect(..)' –
得到,是的,具有相同Id的人。但是,实际上,我认为我的代码中存在一个错误。让我测试并进行更正... – lsibaja