其他分享
首页 > 其他分享> > LINQ笔记-复杂案例

LINQ笔记-复杂案例

作者:互联网

实体:

    public class Person
    {
        public string Name { get; set; }
        public int CompanyID { get; set; }
    }
    public class Company
    {
        public int ID { get; set; }
    }
List<Company> companyList = new List<Company> {
                new Company{ ID=1},
                new Company{ ID=2},
                new Company{ ID=3}
            };
            List<Person> personList = new List<Person> {
                new Person{ CompanyID=1,Name="zhangsan"},
                new Person{ CompanyID=1,Name="lisi"},
                new Person{ CompanyID=2,Name="wangwu"}
            };

内连接:

var list1 = from c in companyList
                       join p in personList on c.ID equals p.CompanyID
                       select new { CompanyID = c.ID, PersonName = p.Name };

左连接:personList的数据放入临时变量personTempList中,并调用DefaultIfEmpty(),意思是为空就使用默认值

var list1 = from c in companyList
                       join p in personList on c.ID equals p.CompanyID into personTempList
                       from pTemp in personTempList.DefaultIfEmpty()
                       select new { CompanyID = c.ID, PersonName = pTemp?.Name };

也可以指定默认值:

var list1 = from c in companyList
                       join p in personList on c.ID equals p.CompanyID into personTempList
                       from pTemp in personTempList.DefaultIfEmpty(new Person { Name="DefaultName"})
                       select new { CompanyID = c.ID, PersonName = pTemp.Name };

未完待续...

标签:Name,CompanyID,personTempList,笔记,public,案例,LINQ,new,ID
来源: https://www.cnblogs.com/fanfan-90/p/12112289.html