如何高效且安全地获取两个集合的共同元素?
在C#中实现集合交集运算主要有三种方式,具体选择需结合数据规模和性能需求。以下是核心实现方法及对比:
通过LINQ扩展方法直接获取交集,代码简洁但需注意元素类型需实现
IEquatable<T>
Equals
GetHashCode
csharp复制varlist1=newList<int>{1,2,3}; varlist2=newList<int>{3,4,5}; varresult=list1.Intersect(list2).ToList();//输出()
利用
HashSet<T>
IntersectWith
csharp复制varhash1=newHashSet<int>{1,2,3}; varhash2=newHashSet<int>{3,4,5}; hash1.IntersectWith(hash2);//hash1变为{3}
通过循环遍历比较元素,适用于自定义类型且需自定义比较逻辑的场景。
csharp复制varcommon=newList<int>(); foreach(variteminlist1) if(list2.Contains(item)) common.Add(item);
方法 | 适用场景 | 性能特点 | 依赖项 |
---|---|---|---|
LINQIntersect | 代码简洁性优先 | O(n)时间复杂度 | System.Linq |
HashSetIntersectWith | 高频交集运算 | O(n)时间复杂度 | System.Collections.Generic |
手动实现 | 自定义比较逻辑 | O(n2)时间复杂度 | 无 |
注意事项:
Equals
GetHashCode
HashSet
Intersect