## List之Union(),Intersect(),Except() 即并集，交集，差集运算。 转

深圳大道

``````using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sample2
{
class Program
{
static void Main(string[] args)
{
//List之Union(),Intersect(),Except() 即并集，交集，差集运算
IList<Student> Students1 = new List<Student>();

IList<Student> Students2 = new List<Student>();

//自定义比较规则
var bingji = Students1.Union(Students2, new StudentListEquality()).ToList();//并集（AB集合所有项）
var jiaoji = Students1.Intersect(Students2, new StudentListEquality()).ToList();//交集 (AB集合共同项)
var chaji = Students1.Except(Students2, new StudentListEquality()).ToList();//差集（A集合有,B没有）

Console.WriteLine("以下是并集的结果");
bingji.ForEach(x =>
{
Console.WriteLine(x.Id.ToString() + "    " + x.Sex.ToString() + "   " + x.Name.ToString() + " " + x.Address.ToString());

});

Console.WriteLine("以下是交集的结果");
jiaoji.ForEach(x =>
{
Console.WriteLine(x.Id.ToString() + "    " + x.Sex.ToString() + "   " + x.Name.ToString() + " " + x.Address.ToString());

});

Console.WriteLine("以下是差集的结果");
chaji.ForEach(x =>
{
Console.WriteLine(x.Id.ToString() + "    " + x.Sex.ToString() + "   " + x.Name.ToString() + " " + x.Address.ToString());

});
}
}

public class Student
{
public Student(int id, bool sex, String name, String address)
{
this.Id = id;
this.Sex = sex;
this.Name = name;
}
public int Id { get; set; }
public bool Sex { get; set; }
public String Name { get; set; }
public String Address { get; set; }

}

public class StudentListEquality : IEqualityComparer<Student>
{
public bool Equals(Student x, Student y)
{
return x.Id == y.Id && x.Name == y.Name && x.Address == y.Address && x.Sex == y.Sex;
}
public int GetHashCode(Student obj)
{
return (obj == null) ? 0 : obj.ToString().GetHashCode();
}
}
}``````

### 深圳大道

jackson0714
2016/08/12
0
0
oracle --union和union all

2015/08/03
377
0
SQL Server T-SQL高级查询

2016/01/06
48
0
SQL集合运算：差集、交集、并集

1、差集( except ) select a from t_a except select a from t_b -- 也可写作： select a from ta where a not in (select a from tb) -- 多个字段时： select a,b from t_a except select ......

2016/11/04
328
0
SQL集合运算：差集、交集、并集

1、差集( except ) select a from t_a except select a from t_b -- 也可写作： select a from ta where a not in (select a from tb) -- 多个字段时： select a,b from t_a except select ......

2016/04/27
90
0

8分钟前
7
0

8分钟前
6
0
Elasticsearch 实战(一) - 简介

JavaEdge
13分钟前
3
0
【jQuery基础学习】11 jQuery性能简单优化

21分钟前
5
0

24分钟前
3
0