C# List的便捷使用获取交集、差集与并集
前言
在C#中,我们有时会需要对两个数据列表进行一些数据的提取、对比之类的特殊操作,此时我们就可以借助 System.Linq 进行快速操作。
我们可以使用 System.Linq(Language Integrated Query)来方便地对List<T>进行交集、差集和并集的操作
1.并集 - Union
并集可以快速获取两个 List 列表中所有不重复的元素的新列表
// using System.Linq;
List<int> list1 = new List<int> { 1, 2, 3, 4 };
List<int> list2 = new List<int> { 3, 4, 5, 6 };
var union = list1.Union(list2).ToList();
// union = new List<int>{ 1, 2, 3, 4, 5, 6};
2.交集 - Intersect
交集可以快速获取到两个 List 列表中重复的元素的新列表
// using System.Linq;
List<int> list1 = new List<int> { 1, 2, 3, 4 };
List<int> list2 = new List<int> { 3, 4, 5, 6 };
var intersect= list1.Intersect(list2).ToList();
// intersect = new List<int>{ 3, 4};
3.差集 - Except
差集会有所特殊,它对应的为从一个列表本身为主体,去对比目标列表中的元素,获取主列表中存在但是不存在目标列表中的元素集合
// using System.Linq;
List<int> list1 = new List<int> { 1, 2, 3, 4 };
List<int> list2 = new List<int> { 3, 4, 5, 6 };
var except= list1.Except(list2).ToList();
// except= new List<int>{ 1, 2,};
扩展
- 在使用这些方法时,确保集合中的元素类型
T实现了IEquatable<T>接口或者有适当的Equals和GetHashCode方法定义,这样才能正确比较元素是否相等。 - LINQ的这些方法默认会对结果进行去重,即结果集中不会包含重复的元素。
- 如果需要考虑元素顺序或执行更复杂的集合运算,可能需要结合其他LINQ方法或自定义比较逻辑。
List<string> fruits1 = new List<string> { "apple", "banana", "orange", "pear" };
List<string> fruits2 = new List<string> { "grape", "banana", "watermelon", "pear" };
List<string> unionFruits = fruits1.Union(fruits2).ToList(); //并集 并集的个数一般不会为0,除非list1和list2中的元素个数都为0
// unionFruits = new List<string>() { "apple", "banana", "orange", "pear", "grape", "watermelon"};
for (int i = 0; i < unionFruits.Count; i++)
{
Debug.Log("扩展并集" + unionFruits[i]);
}
List<string> intersectionFruits = fruits1.Intersect(fruits2).ToList(); //交集 表示两个List都存在的集合
// intersectionFruits = new List<string>() { "banana", "pear",};
for (int i = 0; i < intersectionFruits.Count; i++)
{
Debug.Log("扩展交集" + intersectionFruits[i]);
}
List<string> differenceFruits = fruits1.Except(fruits2).Distinct().ToList(); //差集 表示fruits1存在fruits2不存在的集合
// differenceFruits = new List<string>() { "apple", "orange",};
for (int i = 0; i < differenceFruits.Count; i++)
{
Debug.Log("扩展差集" + differenceFruits[i]);
}
没有人应该止步不前,除非你觉得这样就很好了

浙公网安备 33010602011771号