广告
返回顶部
首页 > 资讯 > 后端开发 > ASP.NET >linq中的连接操作符
  • 148
分享到

linq中的连接操作符

2024-04-02 19:04:59 148人浏览 泡泡鱼
摘要

linq中的连接操作符主要包括Join()和GroupJoin()两个。 一、Join()操作符 Join()操作符非常类似于T-sql中的inner join,它将两个数据源进行连

linq中的连接操作符主要包括Join()和GroupJoin()两个。

一、Join()操作符

Join()操作符非常类似于T-sql中的inner join,它将两个数据源进行连接,根据两个数据源中相等的值进行匹配。例如:可以将产品表和产品类别表进行连接,得到产品名称和与其对应的类型名称。下面看看Join()方法的定义:

public static IEnumerable<TResult> Join<TOuter, TInner, TKEy, TResult>(this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector);
public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector, IEqualityComparer<TKey> comparer);

从Join()方法的定义中可以看到:Join操作符的方法原型非常复杂,从方法原型可以看到,参数outer和inner是需要连接的两个输入集合。其中outer代表的是调用的集合。当Join操作符被调用时,首先列举inner序列中的所有元素,为序列中每一个类型为U的元素调用委托InnerKeySelector,生成一个类型为K的的对象innerKey作为连接关键字。(相当于数据库中的外键),将inner序列中的每一个元素和其对应的连接关键字innerKey存储在一个临时哈希表中;其次列举outer序列中的所有元素,为每一个类型为T的元素调用委托outerKeySelector,生成一个类型为K的对象outKey用作连接关键字,在第一步生成的临时哈希表中查找与outKey相等的对应的innerKey对象,如果找到对应的记录,会将当前outer序列中的类型为T的元素和对应的inner序列中类型为U的元素作为一组参数传递给委托resultSelector,resultSelector会根据这两个参数返回一个类型为V的对象,此类型为V的对象会被添加到Join操作符的输出结果序列中去。Join操作符返回一个类型为IEnumerable<T>的序列。来看下面的例子:

1、新建CateGory和Product两个类,其类定义分别如下:

Category:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConnectOperation
{
    public class Category
    {
        public int Id { get; set; }
        public string CategoryName { get; set; }

        public DateTime CreateTime { get; set; }
    }
}

Product:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConnectOperation
{
    public class Product
    {
        public int Id { get; set; }
        public int CategoryId { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
        public DateTime CreateTime { get; set; }
    }
}

2、在Main()方法中调用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConnectOperation
{
    class Program
    {
        static void Main(string[] args)
        {
            // 初始化数据
            List<Category> listCategory = new List<Category>()
            {
              new Category(){ Id=1,CategoryName="计算机",CreateTime=DateTime.Now.AddYears(-1)},
              new Category(){ Id=2,CategoryName="文学",CreateTime=DateTime.Now.AddYears(-2)},
              new Category(){ Id=3,CategoryName="高校教材",CreateTime=DateTime.Now.AddMonths(-34)},
              new Category(){ Id=4,CategoryName="心理学",CreateTime=DateTime.Now.AddMonths(-34)}
            };
            List<Product> listProduct = new List<Product>()
            {
               new Product(){Id=1,CategoryId=1, Name="C#高级编程第10版", Price=100.67,CreateTime=DateTime.Now},
               new Product(){Id=2,CategoryId=1, Name="Redis开发运维", Price=69.9,CreateTime=DateTime.Now.ADDDays(-19)},
               new Product(){Id=3,CategoryId=2, Name="活着", Price=57,CreateTime=DateTime.Now.AddMonths(-3)},
               new Product(){Id=4,CategoryId=3, Name="高等数学", Price=97,CreateTime=DateTime.Now.AddMonths(-1)},
               new Product(){Id=5,CategoryId=6, Name="国家宝藏", Price=52.8,CreateTime=DateTime.Now.AddMonths(-1)}
            };

            // 1、查询表达式
            var queryExpress = from c in listCategory
                               join p in listProduct on c.Id equals p.CategoryId
                               select new { Id = c.Id, CategoryName = c.CategoryName, ProductName = p.Name, PublishTime = p.CreateTime };
            Console.WriteLine("查询表达式输出:");
            foreach (var item in queryExpress)
            {
                Console.WriteLine($"id:{item.Id},CategoryName:{item.CategoryName},ProductName:{item.ProductName},PublishTime:{item.PublishTime}");
            }
            Console.WriteLine("方法语法输出:");
            // 方法语法
            var queryFun = listCategory.Join(listProduct, c => c.Id, p => p.CategoryId, (c, p) => new { Id = c.Id, CategoryName = c.CategoryName, ProductName = p.Name, PublishTime = p.CreateTime });
            foreach (var item in queryFun)
            {
                Console.WriteLine($"id:{item.Id},CategoryName:{item.CategoryName},ProductName:{item.ProductName},PublishTime:{item.PublishTime}");
            }

            Console.ReadKey();
        }
    }
}

结果:

从结果中可以看出:Join()操作符只会输出两个结合中相同的元素,和T-SQL中的inner join类似。

在T-SQL中除了内连接以外,还有左连接和右连接,那么使用Join()是不是也可以实现左连接和右连接呢?请看下面的例子。

使用Join()实现左连接。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConnectOperation
{
    class Program
    {
        static void Main(string[] args)
        {
            // 初始化数据
            List<Category> listCategory = new List<Category>()
            {
              new Category(){ Id=1,CategoryName="计算机",CreateTime=DateTime.Now.AddYears(-1)},
              new Category(){ Id=2,CategoryName="文学",CreateTime=DateTime.Now.AddYears(-2)},
              new Category(){ Id=3,CategoryName="高校教材",CreateTime=DateTime.Now.AddMonths(-34)},
              new Category(){ Id=4,CategoryName="心理学",CreateTime=DateTime.Now.AddMonths(-34)}
            };
            List<Product> listProduct = new List<Product>()
            {
               new Product(){Id=1,CategoryId=1, Name="C#高级编程第10版", Price=100.67,CreateTime=DateTime.Now},
               new Product(){Id=2,CategoryId=1, Name="Redis开发和运维", Price=69.9,CreateTime=DateTime.Now.AddDays(-19)},
               new Product(){Id=3,CategoryId=2, Name="活着", Price=57,CreateTime=DateTime.Now.AddMonths(-3)},
               new Product(){Id=4,CategoryId=3, Name="高等数学", Price=97,CreateTime=DateTime.Now.AddMonths(-1)},
               new Product(){Id=5,CategoryId=6, Name="国家宝藏", Price=52.8,CreateTime=DateTime.Now.AddMonths(-1)}
            };
            // 1、使用查询表达式实现左连接
            var listLeft = from c in listCategory
                           join p in listProduct on c.Id equals p.CategoryId
                           into cpList
                           from cp in cpList.DefaultIfEmpty()
                           select new
                           {
                               Id = c.Id,
                               CategoryName = c.CategoryName,
                               ProductName = cp == null ? "无产品名称" : cp.Name,
                               PublishTime = cp == null ? "无创建时间" : cp.CreateTime.ToString()
                           };
            foreach (var item in listLeft)
            {
                Console.WriteLine($"id:{item.Id},CategoryName:{item.CategoryName},ProductName:{item.ProductName},PublishTime:{item.PublishTime}");
            }

            Console.ReadKey();
        }
    }
}

结果:

从结果中可以看出:左表listCategory中的数据全部输出了,listCategory中分类为4的在listProduct中没有对应的产品记录,所以该项的ProductName和PublishTime输出为空。

注意:

在左连接中,有可能右表中没有对应的记录,所以使用Select投影操作符的时候要注意判断是否为null,否则程序会报错,看下面的例子:

使用方法语法实现左连接要使用下面要讲的GroupJoin(),所以使用方法语法实现左连接放到GroupJoin()中进行讲解。

右连接

其实实现右连接只需要将上面例子中的左表和右边换一下顺序即可。看下面的例子:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConnectOperation
{
    class Program
    {
        static void Main(string[] args)
        {
            // 初始化数据
            List<Category> listCategory = new List<Category>()
            {
              new Category(){ Id=1,CategoryName="计算机",CreateTime=DateTime.Now.AddYears(-1)},
              new Category(){ Id=2,CategoryName="文学",CreateTime=DateTime.Now.AddYears(-2)},
              new Category(){ Id=3,CategoryName="高校教材",CreateTime=DateTime.Now.AddMonths(-34)},
              new Category(){ Id=4,CategoryName="心理学",CreateTime=DateTime.Now.AddMonths(-34)}
            };
            List<Product> listProduct = new List<Product>()
            {
               new Product(){Id=1,CategoryId=1, Name="C#高级编程第10版", Price=100.67,CreateTime=DateTime.Now},
               new Product(){Id=2,CategoryId=1, Name="Redis开发和运维", Price=69.9,CreateTime=DateTime.Now.AddDays(-19)},
               new Product(){Id=3,CategoryId=2, Name="活着", Price=57,CreateTime=DateTime.Now.AddMonths(-3)},
               new Product(){Id=4,CategoryId=3, Name="高等数学", Price=97,CreateTime=DateTime.Now.AddMonths(-1)},
               new Product(){Id=5,CategoryId=6, Name="国家宝藏", Price=52.8,CreateTime=DateTime.Now.AddMonths(-1)}
            };
            // 使用查询表达式实现右连接
            var listRight = from p in listProduct
                            join c in listCategory on p.CategoryId equals c.Id
                            into pcList
                            from pc in pcList.DefaultIfEmpty()
                            select new
                            {
                                Id = p.Id,
                                CategoryName = pc == null ? "无分类名称" : pc.CategoryName,
                                ProductName = p.Name,
                                PublishTime = p.CreateTime
                            };
            foreach (var item in listRight)
            {
                Console.WriteLine($"id:{item.Id},CategoryName:{item.CategoryName},ProductName:{item.ProductName},PublishTime:{item.PublishTime}");
            }

            Console.ReadKey();
        }
    }
}

结果:

从结果中可以看出:listProduct中的数据全部输出了,listCategory中如果没有相应的记录就输出空值。

注意:

在右连接中也需要和左连接一样进行null值的判断。

二、GroupJoin()操作符

GroupJoin()操作符常用于返回“主键对象-外键对象集合”形式的查询,例如“产品类别-此类别下的所有产品”。

GroupJoin操作符也用于连接两个输入序列,但与Join操作符不同稍有不同,Join操作符在列举outer序列元素时,会将一个outer序列元素和其对应的inner序列元素作为一组参数传递给委托resultSelector委托,这就意味着如果某一个outer序列元素有多个对应的inner序列元素,Join操作符将会分多次将outer序列元素和每一个对应的inner序列元素传递给委托resultSelector。使用GroupJoin操作符时,如果某一个outer序列元素有多个对应的inner序列元素,那么这多个对应的inner序列元素会作用一个序列一次性传递给委托resultSelecotr,可以针对此序列添加一些处理逻辑。下面看看GroupJoin()操作符的定义:

public static IEnumerable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector,
 Func<TInner, TKey> innerKeySelector, Func<TOuter, IEnumerable<TInner>, TResult> resultSelector);
public static IEnumerable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector,
Func<TInner, TKey> innerKeySelector, Func<TOuter, IEnumerable<TInner>, TResult> resultSelector, IEqualityComparer<TKey> comparer);

留意变红的那个委托,注意,与Join操作符的不同点就是一个outer序列中如果有多个对应的inner序列元素,会作为一个集合IEnumerable<TInner>传递到此委托。来看下面的例子:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConnectOperation
{
    class Program
    {
        static void Main(string[] args)
        {
            // 初始化数据
            List<Category> listCategory = new List<Category>()
            {
              new Category(){ Id=1,CategoryName="计算机",CreateTime=DateTime.Now.AddYears(-1)},
              new Category(){ Id=2,CategoryName="文学",CreateTime=DateTime.Now.AddYears(-2)},
              new Category(){ Id=3,CategoryName="高校教材",CreateTime=DateTime.Now.AddMonths(-34)},
              new Category(){ Id=4,CategoryName="心理学",CreateTime=DateTime.Now.AddMonths(-34)}
            };
            List<Product> listProduct = new List<Product>()
            {
               new Product(){Id=1,CategoryId=1, Name="C#高级编程第10版", Price=100.67,CreateTime=DateTime.Now},
               new Product(){Id=2,CategoryId=1, Name="Redis开发和运维", Price=69.9,CreateTime=DateTime.Now.AddDays(-19)},
               new Product(){Id=3,CategoryId=2, Name="活着", Price=57,CreateTime=DateTime.Now.AddMonths(-3)},
               new Product(){Id=4,CategoryId=3, Name="高等数学", Price=97,CreateTime=DateTime.Now.AddMonths(-1)},
               new Product(){Id=5,CategoryId=6, Name="国家宝藏", Price=52.8,CreateTime=DateTime.Now.AddMonths(-1)}
            };

            // 使用GroupJoin()实现左连接
            var listLeftFun = listCategory.GroupJoin(listProduct, c => c.Id, p => p.CategoryId, (c, listp) => listp.DefaultIfEmpty(new Product()).Select(z =>
                 new
                 {
                     Id = c.Id,
                     CategoryName = c.CategoryName,
                     ProduceName = z.Name,
                     ProductPrice = z.Price
                 })).ToList();
            foreach (var item in listLeftFun)
            {
                foreach (var p in item)
                {
                    Console.WriteLine($"CategoryId:{p.Id},CategoryName:{p.CategoryName},ProduceName:{p.ProduceName},ProductPrice:{p.ProductPrice}");
                }
            }
            Console.ReadKey();
        }

    }
}

结果:

结果可以看出:使用GroupJoin()操作符可以用Lambda表达式实现左连接。

右连接

只需要调整上面例子中两张表的顺序即可。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConnectOperation
{
    class Program
    {
        static void Main(string[] args)
        {
            // 初始化数据
            List<Category> listCategory = new List<Category>()
            {
              new Category(){ Id=1,CategoryName="计算机",CreateTime=DateTime.Now.AddYears(-1)},
              new Category(){ Id=2,CategoryName="文学",CreateTime=DateTime.Now.AddYears(-2)},
              new Category(){ Id=3,CategoryName="高校教材",CreateTime=DateTime.Now.AddMonths(-34)},
              new Category(){ Id=4,CategoryName="心理学",CreateTime=DateTime.Now.AddMonths(-34)}
            };
            List<Product> listProduct = new List<Product>()
            {
               new Product(){Id=1,CategoryId=1, Name="C#高级编程第10版", Price=100.67,CreateTime=DateTime.Now},
               new Product(){Id=2,CategoryId=1, Name="Redis开发和运维", Price=69.9,CreateTime=DateTime.Now.AddDays(-19)},
               new Product(){Id=3,CategoryId=2, Name="活着", Price=57,CreateTime=DateTime.Now.AddMonths(-3)},
               new Product(){Id=4,CategoryId=3, Name="高等数学", Price=97,CreateTime=DateTime.Now.AddMonths(-1)},
               new Product(){Id=5,CategoryId=6, Name="国家宝藏", Price=52.8,CreateTime=DateTime.Now.AddMonths(-1)}
            };
            var listRightFun = listProduct.GroupJoin(listCategory, p => p.CategoryId, c => c.Id, (p, listc) => listc.DefaultIfEmpty(new Category()).Select(z =>
            new
            {
                id = p.Id,
                ProductName = p.Name,
                ProductPrice = p.Price,
                CategoreName = z.CategoryName
            }));
            foreach (var item in listRightFun)
            {
                foreach (var p in item)
                {
                    Console.WriteLine($"id:{p.id},ProduceName:{p.ProductName},ProductPrice:{p.ProductPrice},CategoryName:{p.CategoreName}");
                }
            }
        }
    }
}

结果:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。

--结束END--

本文标题: linq中的连接操作符

本文链接: https://www.lsjlt.com/news/141982.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • linq中的连接操作符
    linq中的连接操作符主要包括Join()和GroupJoin()两个。 一、Join()操作符 Join()操作符非常类似于T-SQL中的inner join,它将两个数据源进行连...
    99+
    2022-11-13
  • linq中的转换操作符
    目录一、AsEnumerable操作符二、ToArray操作符三、ToDictionary操作符四、ToList操作符五、ToLookUp操作符六、Cast操作符这些转换操作符将集合...
    99+
    2022-11-13
  • linq中的聚合操作符
    目录一、Aggregate操作符二、Average操作符1、直接求基本类型集合的平均值2、求listProduct集合中价格的平均值三、Count操作符四、LongCount操作符五...
    99+
    2022-11-13
  • linq中的限定操作符
    限定操作符运算返回一个Boolean值,该值指示序列中是否有一些元素满足条件或者是否所有元素都满足条件。 一、All操作符 All方法用来确定是否序列中的所有元素都满足条件。看下面的...
    99+
    2022-11-13
  • linq中的元素操作符
    目录一、Fitst操作符二、FirstOrDefault操作符三、Last操作符四、LastOrDefault操作符五、ElementAt操作符六:ElementAtOrDefaul...
    99+
    2022-11-13
  • linq中的分区操作符
    Linq中的分区指的是在不重新排列元素的情况下,将输入序列划分为两部分,然后返回其中一个部分的操作。 一、Take操作符 Take(int n)表示将从序列的开头返回数量为n的连续元...
    99+
    2022-11-13
  • linq中的分组操作符
    分组是根据一个特定的值将序列中的元素进行分组。LINQ只包含一个分组操作符:GroupBy。GroupBy操作符类似于T-SQL语言中的Group By语句。来看看GroupBy的方...
    99+
    2022-11-13
  • linq中的串联操作符
    串联是一个将两个集合连接在一起的过程。在Linq中,这个过程通过Concat操作符实现。Concat操作符用于连接两个集合,生成一个新的集合。来看看Concat操作符的定义: pub...
    99+
    2022-11-13
  • LINQ操作符SelectMany的用法
    SelectMany操作符提供了将多个from子句组合起来的功能,相当于数据库中的多表连接查询,它将每个对象的结果合并成单个序列。 示例: student类: using ...
    99+
    2022-11-13
  • linq中的限定操作符怎么用
    本篇内容介绍了“linq中的限定操作符怎么用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!限定操作符运算返回一个Boolean值,该值指示序...
    99+
    2023-06-29
  • Linq 中如何使用Contains操作符
    Linq 中如何使用Contains操作符,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。投影和排序您可能还注意到我在之前的示例中暗藏了一个投影。在使用 Max 操作符之前,LI...
    99+
    2023-06-17
  • LINQ中有哪些查询操作符
    这篇文章给大家介绍LINQ中有哪些查询操作符,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。操作符和LINQLINQ自身功能非常强大,无论使用的是LINQto XML、LINQto DataSets、LINQto Ent...
    99+
    2023-06-17
  • linq中聚合操作符怎么用
    这篇文章给大家分享的是有关linq中聚合操作符怎么用的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。一、Aggregate操作符Aggregate操作符对集合值执行自定义聚合运算。来看看Aggregate的定义:p...
    99+
    2023-06-29
  • LINQ排序操作符用法
    Linq中的排序操作符包括OrderBy、OrderByDescending、ThenBy、ThenByDescending和Reverse,提供了升序或者降序排序。 一、Orde...
    99+
    2022-11-13
  • LINQ投影操作符Select与限制操作符where介绍
    一、什么是LINQ它可以用来做什么 语言集成查询(Language Integrated Query,LINQ)是一系列标准查询操作符的集合,这些操作符几乎对每一种数据源的导航、过滤...
    99+
    2022-11-13
  • LINQ排序操作符怎么使用
    这篇文章主要介绍了LINQ排序操作符怎么使用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇LINQ排序操作符怎么使用文章都会有所收获,下面我们一起来看看吧。Linq中的排序操作符包括OrderBy、OrderB...
    99+
    2023-06-29
  • SQL中的连接操作
    本篇内容主要讲解“SQL中的连接操作”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“SQL中的连接操作”吧! 利用连接操作,可以根据表与表之间的逻辑联系从两个或...
    99+
    2022-10-18
  • C#如何使用LINQ查询操作符
    这篇文章主要讲解了“C#如何使用LINQ查询操作符”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C#如何使用LINQ查询操作符”吧!连表操作符1、内连接使用 join 子句 根据特定的条件合...
    99+
    2023-07-02
  • MySQL中的连接操作:内连接、外连接和交叉连接详解
    MySQL中的连接操作:内连接、外连接和交叉连接详解在MySQL数据库中,连接操作是一种常用的操作技术,用于将两个或多个表中的数据按照一定的条件进行合并。连接操作可以帮助我们处理复杂的数据查询和分析需求。在MySQL中,我们通常使用内连接、...
    99+
    2023-10-22
    连接操作 内连接 外连接
  • Linq中怎么实现连接查询
    今天就跟大家聊聊有关Linq中怎么实现连接查询,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。Linq连接查询之前先建立两个查询:using (DataClassesData...
    99+
    2023-06-17
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作