C#中差集(Except)并集(Union)以及交集(Intersect)
值类型的差集并集以及交集
值类型的操作相对比较简单,直接调用集合方法即可,如下
//首选添加两个集合,存放值类型数据,此处以int为例
List<int> list1 = new List<int>() { 1, 5, 9, 7, 3 };
List<int> list2 = new List<int>() { 4, 0, 2, 8, 3, 7 };
//求并集
var reslt = list1.Union(list2);
Console.WriteLine("并集结果为:{0}", string.Join(",", reslt));
//求交集
reslt = list1.Intersect(list2);
Console.WriteLine("交集结果为:{0}", string.Join(",", reslt));
//求差集(前者中有,后者不存在的数据)
reslt = list1.Except(list2);
Console.WriteLine("list1与list2的差集结果为:{0}", string.Join(",", reslt));
reslt = list2.Except(list1);
Console.WriteLine("list2与list1的差集结果为:{0}", string.Join(",", reslt));这里要注意,差集并不是我们上学学的那种,直接得出结果,而是需要左右各对比差集一次,才能求出两个数组最终的差集
引用类型的差集并集以及交集
引用类型就要稍微麻烦一点了,首先我们需要创建一个比较器(继承自IEqualityComparer接口)
/// <summary>
/// 定义一个学生的比较器
/// </summary>
class StudentComparer : IEqualityComparer<Student>
{
public bool Equals(Student x, Student y)
{
return x.Id == y.Id;
}
public int GetHashCode(Student obj)
{
if (obj == null)
return 0;
return obj.Id.GetHashCode();
}
}然后再求差集、并集以及交集时,传入该比较器的实例即可
//添加两个集合,存放引用类型数据,此处以Student为例
List<Student> list3 = new List<Student>()
{
new Student(){Id=0, Name="张三",Sex=Sex.Man },
new Student(){Id=1, Name="王五",Sex=Sex.Woman },
new Student(){Id=2, Name="李四",Sex=Sex.Man },
};
List<Student> list4 = new List<Student>()
{
new Student(){Id=0, Name="张三",Sex=Sex.Man },
new Student(){Id=3, Name="李四",Sex=Sex.Man },
};
//求并集
var reslt2 = list3.Union(list4, new StudentComparer());
foreach (var item in reslt2)
{
Console.WriteLine(item.ToString());
}
//求交集
reslt2 = list3.Intersect(list4, new StudentComparer());
Console.WriteLine("引用类型交集结果为:");
foreach (var item in reslt2)
{
Console.WriteLine(item.ToString());
}
//求差集(前者中有,后者不存在的数据)
reslt2 = list3.Except(list4, new StudentComparer());
Console.WriteLine("list3与list4的差集结果为::");
foreach (var item in reslt2)
{
Console.WriteLine(item.ToString());
}
reslt2 = list4.Except(list3, new StudentComparer());
Console.WriteLine("list4与list3的差集结果为::");
foreach (var item in reslt2)
{
Console.WriteLine(item.ToString());
}扩展:若引用对象需要同时判断多个属性才能确定是否为一个对象时怎么写比较器呢?
/// <summary>
/// 定义一个学生的比较器
/// </summary>
class XXComparer : IEqualityComparer<XX>
{
public bool Equals(XXx, XXy)
{
return x.属性1== y.属性1 && x.属性2==y.属性2......;
}
public int GetHashCode(Student obj)
{
if (obj == null)
return 0;
return obj.Id.GetHashCode();
}
}
川公网安备 51010702003150号
留下您的脚步
最近评论