C# List.Join方法

最近在研究C#泛型集合的时候发现了List.Join方法,这个方法与C#中的string.Join方法还有js中的join方法不一样,不是根据分隔符链接字符串,而是根据两个对象关联起来生成新的数据。

List.Join方法更像SQL 中的JOIN连接,该方法是根据两个泛型集合之间的关系,将这两个集合合并后获取新的集合。而SQL的JOIN 则是根据两个或多个表中的列之间的关系,从这些表中查询数据。(PS:具体可以参考微软官方MSDN的说明)

这是整理后的官方范例代码(代码在控制台应用程序中运行):

    /*宠物主人*/
    class Person
    {
        public string Name { get; set; }
    }
    /*宠物*/
    class Pet
    {
        public string Name { get; set; }
        public Person Owner { get; set; }
    }
    static void Main(string[] args)
    {
        /*宠物主人*/
        Person magnus = new Person { Name = "Hedlund, Magnus" };
        Person terry = new Person { Name = "Adams, Terry" };
        Person charlotte = new Person { Name = "Weiss, Charlotte" };

        /*宠物*/
        Pet barley = new Pet { Name = "Barley", Owner = terry };
        Pet boots = new Pet { Name = "Boots", Owner = terry };
        Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte };
        Pet daisy = new Pet { Name = "Daisy", Owner = magnus };

        /*宠物主人列表集合*/
        List<Person> people = new List<Person> { magnus, terry, charlotte };
        /*宠物列表集合*/
        List<Pet> pets = new List<Pet> { barley, boots, whiskers, daisy };

        /*          
         * Create a list of Person-Pet pairs where 
         * each element is an anonymous type that contains a
         * Pet's name and the name of the Person that owns the Pet.
         * 创建一个包含 "主人-宠物" 这样对应对象的列表
         * ,其中每个对象元素都是包含宠物名字和宠物主人名字的匿名类型
        */            
        var query = people.Join(pets, person => person, pet => pet.Owner
        , (person, pet) => new { OwnerName = person.Name, Pet = pet.Name });

        /*循环输出最终结果 格式:宠物主人名-宠物名*/
        foreach (var obj in query)
        {
            Console.WriteLine("{0} - {1}", obj.OwnerName, obj.Pet);
        }

        Console.ReadKey();
    }

最终控制台输出的结果如下:

输出结果

下面使用SQL语句JOIN连接查询,从而模拟出List.Join方法的同等效果,其中有Person和Pet这两张表,根据Pet宠物表的PID关联Person宠物主人表的ID。

Person表数据如下:

idName
1Hedlund, Magnus
2Adams, Terry
3Weiss, Charlotte

Pet表数据如下:

idNamepid
1Daisy1
2Barley2
3Boots2
4Whiskers3

查询语句如下:

SELECT P.Name+' - '+PT.Name AS '宠物主人 - 宠物名称'
FROM Person AS P JOIN Pet AS PT 
ON P.Id=PT.PID

查询结果如下:

宠物主人 – 宠物名称
Hedlund, Magnus – Daisy
Adams, Terry – Barley
Adams, Terry – Boots
Weiss, Charlotte – Whiskers

最终结果和上面使用List.Join方法获取的一模一样吧。




原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/98346.html

(0)
上一篇 2021年8月21日
下一篇 2021年8月21日

相关推荐

发表回复

登录后才能评论