LINQ的内部联接、分组联接和左外部联接

最近在优化定时任务相关的代码,建议是把总查询放到内存中去坐,尽量减少打开的数据库连接

1. 内连接

指的是结果生成两张表可以连接的部分

cs 复制代码
private void button1_Click_1(object sender, EventArgs e)
        {
            //初始化Student数组
            Student[] arrStu = new Student[]{
                new Student{ID=1,SName="zhangsan",Age=20},
                new Student{ID=2,SName="lisi",Age=21},
                new Student{ID=3,SName="wangwu",Age=23},
                new Student{ID=4,SName="liuliu",Age=24},
            };
            //初始化Product数组
            Product[] arrPro = new Product[]{
                new Product{ID=1,PName="Apple",Price=2.25},
                new Product{ID=2,PName="Orange",Price=5.25},
                new Product{ID=3,PName="Banana",Price=7.5},
                new Product{ID=4,PName="StrawBerry",Price=6.5},
            };
            //标准查询运算符
            var query = arrStu.Join(arrPro, s => s.ID, p => p.ID, (s, p) =>new { s.SName, s.Age, p.PName, p.Price });
            StringBuilder sbRes = new StringBuilder();
            //打印
            foreach (var item in query)
            {
                sbRes.AppendFormat("SName:{0},Age:{1},PName:{2},Price:{3}", item.SName, item.Age, item.PName, item.Price);
                sbRes.AppendLine();
            }
            MessageBox.Show(sbRes.ToString());
        }

或者另外一种写法

cs 复制代码
            //LINQ语句
            var query = from sItem in arrStu
                        join pItem in arrPro
                        on sItem.ID equals pItem.ID
                        select new { sItem.SName, sItem.Age, pItem.PName, pItem.Price };//Select后面接一个匿名对象 
           

2. 分组连接

第一个集合中的每个元素与第二个集合中的一组相关元素进行配对

使用 into关键词

cs 复制代码
Person magnus = new(FirstName: "Magnus", LastName: "Hedlund");
Person terry = new("Terry", "Adams");
Person charlotte = new("Charlotte", "Weiss");
Person arlene = new("Arlene", "Huff");

List<Person> people = new() { magnus, terry, charlotte, arlene };

List<Pet> pets = new()
{
    new(Name: "Barley", Owner: terry),
    new("Boots", terry),
    new("Whiskers", charlotte),
    new("Blue Moon", terry),
    new("Daisy", magnus),
};

// Create a list where each element is an anonymous type
// that contains the person's first name and a collection of
// pets that are owned by them.
var query =
    from person in people
    join pet in pets on person equals pet.Owner into gj
    select new
    {
        OwnerName = person.FirstName,
        Pets = gj
    };

foreach (var v in query)
{
    // Output the owner's name.
    Console.WriteLine($"{v.OwnerName}:");

    // Output each of the owner's pet's names.
    foreach (var pet in v.Pets)
    {
        Console.WriteLine($"  {pet.Name}");
    }
}

/* Output:
     Magnus:
       Daisy
     Terry:
       Barley
       Boots
       Blue Moon
     Charlotte:
       Whiskers
     Arlene:
 */
  1. 左外连接

简单理解就是,基于第一张表,无论第二章表是否有匹配项,都放进去

左连接的数据 一定 大于等于 内连接

cs 复制代码
Person magnus = new("Magnus", "Hedlund");
Person terry = new("Terry", "Adams");
Person charlotte = new("Charlotte", "Weiss");
Person arlene = new("Arlene", "Huff");

Pet barley = new("Barley", terry);
Pet boots = new("Boots", terry);
Pet whiskers = new("Whiskers", charlotte);
Pet bluemoon = new("Blue Moon", terry);
Pet daisy = new("Daisy", magnus);

// Create two lists.
List<Person> people = new() { magnus, terry, charlotte, arlene };
List<Pet> pets = new() { barley, boots, whiskers, bluemoon, daisy };

var query =
    from person in people
    join pet in pets on person equals pet.Owner into gj
    from subpet in gj.DefaultIfEmpty()
    select new
    {
        person.FirstName,
        PetName = subpet?.Name ?? string.Empty
    };

foreach (var v in query)
{
    Console.WriteLine($"{v.FirstName + ":",-15}{v.PetName}");
}

record class Person(string FirstName, string LastName);
record class Pet(string Name, Person Owner);

// This code produces the following output:
//
// Magnus:        Daisy
// Terry:         Barley
// Terry:         Boots
// Terry:         Blue Moon
// Charlotte:     Whiskers
// Arlene:

reference:

  1. 执行左外部联接(C# 中的 LINQ) - C# | Microsoft Learn
相关推荐
我是唐青枫1 小时前
C#.NET ref struct 深度解析:语义、限制与最佳实践
c#·.net
火一线2 小时前
【C#知识点详解】基类、抽象类、接口类型变量与子类实例的归纳总结
开发语言·c#
Lv11770082 小时前
Visual Studio 中的密封类和静态类
ide·笔记·c#·visual studio
武藤一雄2 小时前
[奇淫巧技] WPF篇 (长期更新)
windows·microsoft·c#·.net·wpf
c#上位机4 小时前
halcon窗口显示带有箭头的直线
计算机视觉·c#·halcon
秦苒&4 小时前
【C语言指针四】数组指针变量、二维数组传参本质、函数指针变量、函数指针数组
c语言·开发语言·c++·c#
秋雨雁南飞5 小时前
C# 字符串占位
开发语言·c#
正运动技术5 小时前
PC强实时运动控制(一):C#的EtherCAT总线初始化(上)
c#·运动控制·正运动技术·运动控制器·ethercat·正运动·运动控制内核
d111111111d6 小时前
在STM32中,中断服务函数的命名有什么要求?
笔记·stm32·单片机·嵌入式硬件·学习·c#
极客智造7 小时前
深入解析 C# Type 类:解锁反射与动态编程的核心
c#·反射