zoukankan      html  css  js  c++  java
  • Linq查询 Join与GroupJoin

    用处:当需要将两张表根据某个属性进行合并

    1.两张表结构

    class Person
    {
        public int CityID { set; get; }
        public string pName { set; get; }
    }
    class City
    {
        public int CityNum{ set; get; }
        public string cName { set; get; }
    }

    2.由两个类构成的数据

    Person[] persons = new Person[]
        {
            new Person{ CityID = 1, pName = "ABC" ,Age = 22 },
            new Person{ CityID = 1, pName = "EFG" ,Age = 21 },
            new Person{ CityID = 2, pName = "HIJ" ,Age = 19 },
            new Person{ CityID = 3, pName = "KLM" ,Age = 19 },
            new Person{ CityID = 3, pName = "NOP" ,Age = 20 },
            new Person{ CityID = 4, pName = "QRS" ,Age = 23 },
            new Person{ CityID = 5, pName = "TUV" ,Age = 19 }
        };
    City[] cities = new City[]
        {
            new City{ CityNum = 1, cName = "Guangzhou" },
            new City{ CityNum = 2, cName = "Shenzhen" },
            new City{ CityNum = 3, cName = "Beijing" }
        };

    3. 当使用 Join , CityID 没有和 CityNum 对应的时候 将被忽略,返回的 persons 少于原来的条数

    var result =  persons.Join(cities, p => p.CityID, c => c.CityNum, (p, c) => new { PName = p.pName, Age = p.Age, CName = c.cName});

    4.当使用 GroupJoin, CityID 没有和 CityNum 对应的时候仍然保留,返回的 persons 还是原来的条数,只是部分字段为空

    var result = persons.GroupJoin(cities, p => p.CityID, c => c.CityNum, (p, c) => new { PName = p.pName, Age = p.Age, Cities = c });
  • 相关阅读:
    windows补丁更新列表
    centos7网卡配置vlan
    exp备份工具使用说明
    windows系统SSL/TLS漏洞修复
    CDH平台:ZooKeeper 未授权访问【原理扫描】漏洞修复
    MySQL升级至5.7.35问题处理过程
    10fb does not support flow control autoneg问题处理
    vCenter异常日志:pg_tblspc找不到数据文件
    tcpdump命令
    排序算法总结
  • 原文地址:https://www.cnblogs.com/HansZimmer/p/13692074.html
Copyright © 2011-2022 走看看