1 回答
![?](http://img1.sycdn.imooc.com/54584f3100019e9702200220-100-100.jpg)
TA贡献1807条经验 获得超9个赞
最简单的版本(使用 Intersect):
public bool Compare(List<T> firstCollection, List<T> secondCollection)
{
return firstCollection.Intersect(secondCollection).Any();
}
唯一的警告是在调用中T实现IEquatable<T>或传递自定义。还要确保与IEqualityComparer<T>IntersectGetHashCodeEquals
编辑1:
这个使用 Dictionary 的版本不仅会提供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);
}
- 1 回答
- 0 关注
- 173 浏览
添加回答
举报