• 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 };

    未完待续...

  • 相关阅读:
    安装mysql
    date, Calendar
    心态
    jdbc ---- DBUTilDao 类
    jdbc--------JdbcUtilDao 类
    Python与C/C++相互调用
    用链表和数组实现HASH表,几种碰撞冲突解决方法
    用链表实现消息队列
    文件系统的发展
    [深度学习]开源的深度学习框架
  • 原文地址:https://www.cnblogs.com/fanfan-90/p/12112289.html
Copyright © 2020-2023  润新知