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 });
  • 相关阅读:
    秒杀多线程第十篇 生产者消费者问题 (续)
    平面最近点距离问题(分治法)
    阿里神马搜索算法实习生 二面
    37. Sudoku Solver
    52. N-Queens II(数个数)
    51. N-Queens
    89. Gray Code(公式题)
    22. Generate Parentheses(回溯)
    回溯总结
    40. Combination Sum II
  • 原文地址:https://www.cnblogs.com/HansZimmer/p/13692074.html
Copyright © 2011-2022 走看看