C# 检查列表是否不相交
我需要检查两个列表是否有任何相同的元素。我只需要一个是/否-我不需要公共元素的实际列表 我可以使用C# 检查列表是否不相交,c#,disjoint-sets,C#,Disjoint Sets,我需要检查两个列表是否有任何相同的元素。我只需要一个是/否-我不需要公共元素的实际列表 我可以使用Enumerable.Intersect(),但这实际上返回了一组匹配项,这似乎需要额外的开销是否有更好的方法检查列表是否不相交? 我的列表实际上恰好是List,但这并不重要,如果方便的话,我可以使用类似HashSet(比如)的东西。i、 例如,我不想不必要地限制潜在的解决方案 格拉齐·米勒 最简单的版本(使用Intersect): 在相交后粘贴.Any()。Enumerable.Intersec
Enumerable.Intersect()
,但这实际上返回了一组匹配项,这似乎需要额外的开销是否有更好的方法检查列表是否不相交?
我的列表实际上恰好是
List
,但这并不重要,如果方便的话,我可以使用类似HashSet
(比如)的东西。i、 例如,我不想不必要地限制潜在的解决方案
格拉齐·米勒
最简单的版本(使用Intersect):
在相交后粘贴.Any()。Enumerable.Intersect().Any()
应该(无论如何)在找到第一个相交后立即返回,而不是返回整个集合。
public bool Compare(List<T> firstCollection, List<T> secondCollection)
{
return firstCollection.Intersect(secondCollection).Any();
}
public bool CompareUsingDictionary(IEnumerable<T> firstCollection, IEnumerable<T> secondCollection)
{
// Implementation needs overiding GetHashCode methods of the object base class in the compared type
// Obviate initial test cases, if either collection equals null and other doesn't then return false. If both are null then return true.
if (firstCollection == null && secondCollection != null)
return false;
if (firstCollection != null && secondCollection == null)
return false;
if (firstCollection == null && secondCollection == null)
return true;
// Create a dictionary with key as Hashcode and value as number of occurences
var dictionary = new Dictionary<int, int>();
// If the value exists in first list , increase its count
foreach (T item in firstCollection)
{
// Get Hash for each item in the list
int hash = item.GetHashCode();
// If dictionary contains key then increment
if (dictionary.ContainsKey(hash))
{
dictionary[hash]++;
}
else
{
// Initialize he dictionary with value 1
dictionary.Add(hash, 1);
}
}
// If the value exists in second list , decrease its count
foreach (T item in secondCollection)
{
// Get Hash for each item in the list
int hash = item.GetHashCode();
// If dictionary contains key then decrement
if (dictionary.ContainsKey(hash))
{
dictionary[hash]--;
}
else
{
return false;
}
}
// Check whether any value is 0
return dictionary.Values.Any(numOfValues => numOfValues == 0);
}