c# - 检查列表是否不相交
问题描述
我需要检查两个列表是否有任何共同的元素。我只需要一个是/否- 我不需要常见元素的实际列表。
我可以使用Enumerable.Intersect()
,但这确实返回了一组匹配项,这似乎需要额外的开销。有没有更好的方法来检查列表是否不相交?
我的清单确实碰巧是,List<T>
但这并不重要,HashSet
如果更方便的话,我可以使用类似(比如说)的东西。即,我不想不必要地限制潜在的解决方案。
Grazie Mille
解决方案
最简单的版本(使用相交):
public bool Compare(List<T> firstCollection, List<T> secondCollection)
{
return firstCollection.Intersect(secondCollection).Any();
}
唯一需要注意的是要么在调用中T
实现IEquatable<T>
或传递自定义。还要确保它被覆盖IEqualityComparer<T>
Intersect
GetHashCode
Equals
编辑1:
这个使用字典的版本不仅提供boolean
比较,还提供元素。在这个解决方案Dictionary
中,最终将包含与相交元素数量相关的数据,其中一个集合中的元素数量而不是另一个集合中的元素数量,因此相当耐用。该解决方案也有IEquatable<T>
要求
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);
}
推荐阅读
- json - 在身份验证之前在 AWS buildspec 中使用 jq - 最佳实践?
- python - 根据条件从列表中列出
- apache-ranger - 使用 Apache Knox + Ranger 进行 REST API 级别授权
- javascript - Javascript - 如何优化我的数独?
- asp.net - .NET Framework 从 2.0 迁移到 4.8
- forms - 来自数组的symfony表单集合类型
- ui-automation - 触发器:个人工作区中的页面不可用
- php - Blade:在 foreach 循环中选择选项
- java - Kotlin Generics - 递归泛型 - 转换擦除类型的实例失败
- spring - SimpleJpaRepository (CrudRepository) 和 @Transactional