准备两个类
class Person { public string Name { set; get; } public int Age { set; get; } } class Dog { public string Name { get; set; } public string Master { get; set; } }
插入数据
List<Person> personList; List<Dog> dogList; public Form1() { InitializeComponent(); personList = new List<Person>() { new Person (){ Name="Alex",Age=12}, new Person (){ Name="Peter",Age=16}, new Person (){ Name="Zack",Age=12}, new Person (){ Name="TJ",Age=13}, }; dogList = new List<Dog>() { new Dog (){ Name="dog1",Master="Alex"}, new Dog (){ Name="dog2",Master="TJ"}, new Dog (){ Name="dog3",Master="Alex"} }; }
内连接
private void button1_Click(object sender, EventArgs e) { //内连接 dataGridView1.DataSource = (from people in personList join dogs in dogList on people.Name equals dogs.Master select new { Master = people.Name, Dod = dogs.Name }).ToList(); }
分组连接
private void button1_Click(object sender, EventArgs e) { //分组连接 dataGridView1.DataSource = (from people in personList join dogs in dogList on people.Name equals dogs.Master into gc from gci in gc select new { Master = people.Name, Dod = gci.Name }).ToList(); }
左外连接
private void button1_Click(object sender, EventArgs e) { //左外连接 dataGridView1.DataSource = (from people in personList join dogs in dogList on people.Name equals dogs.Master into gc from gci in gc.DefaultIfEmpty() select new { Master = people.Name, Dod = (gci==null?"NULL":gci.Name) }).ToList(); }