Linq中连接主要有组连接、内连接、左外连接、交叉连接四种。各个用法如下。

注:本文内容主要来自《Linq实战》,本例中用到的对象请见文章底部。

1、 组连接

组连接是与分组查询是一样的。即根据分组得到结果。 如下例,根据publisther分组得到结果。

使用组连接的查询语句如下:

//使用组连接
var GroupQuery = from publisher in SampleData.Publishers
                 join book in SampleData.Books
                 on publisher equals book.Publisher into publisherBooks
                 select new
                 {
                   PublisherName = publisher.Name,
                   Books = publisherBooks
                 };

与上边等同的GroupBy语句如下:

 //使用Group
 var QueryByGroup = from book in SampleData.Books
                    group book by book.Publisher into grouping
                    select new
                    {
                         PublisherName = grouping.Key.Name,
                         Books = grouping
                    };

2、内连接

内连接与SqL中inner join一样,即找出两个序列的交集。如下例找出book中的Publisher存在于SampleData.Publishers的资料。

内连接查询语句如下:


//join查询语句
var joinQuery = from publisher in SampleData.Publishers
                join book in SampleData.Books
                on publisher equals book.Publisher
                select new
                {
                    PublisherName = publisher.Name,
                    BookName = book.Title
                };

与上边等同的查询操作符语句如下:

//join操作符语句
     SampleData.Publishers.Join(
                SampleData.Books,               //join 对象
                publisher => publisher,         //外部的key
                book => book.Publisher,         //内部的key
                (publisher, book) => new        //结果
                {
                    PublisherName = publisher.Name,
                    BookName = book.Title
                });

3、左外连接

左外连接与SqL中left join一样。如下例找出根据publisher中找出SampleData.Publishers中所有资料和book中存在于publisher的资料。

左外连接查询语句如下:

//left join, 为空时用default
 var leftJoinQuerybyDefault = from publisher in SampleData.Publishers
                              join book in SampleData.Books
                              on publisher equals book.Publisher into publisherBooks
                              from book in publisherBooks.DefaultIfEmpty()
                              select new
                              {
                                    PublisherName = publisher.Name,
                                    BookName = (book == default(Book)) ? "no book" : book.Title
                              };

注:上例中使用了DefaultIfEmpty操作符,它能够为实序列提供一个默认的元素。DefaultIfEmpty使用了泛型中的default关键字。default关键字对于引用类型将返回null,而对于值类型则返回0。对于结构体类型,则会根据其成员类型将它们相应地初始化为null(引用类型)或0(值类型)。

我们可以不使用default关键字,但在要DefaultIfEmpty中给定当空时的默认对象值。语句如下:

//left join, 为空时使用默认对象
 var leftJoinQuery = from publisher in SampleData.Publishers
                     join book in SampleData.Books
                     on publisher equals book.Publisher into publisherBooks
                     from book in publisherBooks.DefaultIfEmpty(
                       new Book { Title = "" }                         //设置为空时的默认值
                     )
                    select new
                    {
                        PublisherName = publisher.Name,
                        BookName = book.Title
                    };

4、交叉连接

交叉连接与SqL中Cross join一样。如下例中找出SampleData.Publishers与SampleData.Books的交叉连接。

交叉连接查询语句:

            var crossJoinQuery = from publisher in SampleData.Publishers
                                 from book in SampleData.Books
                                 select new
                                 {
                                     PublisherName = publisher.Name,
                                     BookName = book.Title
                                 };

查询操作符语句:

            //不使用查询表达式
            SampleData.Publishers.SelectMany(publisher => SampleData.Books.Select(
                book => new
                {
                    PublisherName = publisher.Name,
                    BookName = book.Title
                }
                ));

本像用到的对象:

  static public class SampleData
  {
    static public Publisher[] Publishers =
    {
      new Publisher {Name="FunBooks"},
      new Publisher {Name="Joe Publishing"},
      new Publisher {Name="I Publisher"}
    };     static public Author[] Authors =
    {
      new Author {FirstName="Johnny", LastName="Good"},
      new Author {FirstName="Graziella", LastName="Simplegame"},
      new Author {FirstName="Octavio", LastName="Prince"},
      new Author {FirstName="Jeremy", LastName="Legrand"}
    };     static public Subject[] Subjects =
    {
      new Subject {Name="Software development"},
      new Subject {Name="Novel"},
      new Subject {Name="Science fiction"}
    };     static public Book[] Books =
    {
      new Book {
        Title="Funny Stories",
        Publisher=Publishers[0],
        Authors=new[]{Authors[0], Authors[1]},
        PageCount=101,
        Price=25.55M,
        PublicationDate=new DateTime(2004, 11, 10),
        Isbn="0-000-77777-2",
        Subject=Subjects[0]
      },
      new Book {
        Title="LINQ rules",
        Publisher=Publishers[1],
        Authors=new[]{Authors[2]},
        PageCount=300,
        Price=12M,
        PublicationDate=new DateTime(2007, 9, 2),
        Isbn="0-111-77777-2",
        Subject=Subjects[0]
      },
      new Book {
        Title="C# on Rails",
        Publisher=Publishers[1],
        Authors=new[]{Authors[2]},
        PageCount=256,
        Price=35.5M,
        PublicationDate=new DateTime(2007, 4, 1),
        Isbn="0-222-77777-2",
        Subject=Subjects[0]
      },
      new Book {
        Title="All your base are belong to us",
        Publisher=Publishers[1],
        Authors=new[]{Authors[3]},
        PageCount=1205,
        Price=35.5M,
        PublicationDate=new DateTime(2006, 5, 5),
        Isbn="0-333-77777-2",
        Subject=Subjects[2]
      },
      new Book {
        Title="Bonjour mon Amour",
        Publisher=Publishers[0],
        Authors=new[]{Authors[1], Authors[0]},
        PageCount=50,
        Price=29M,
        PublicationDate=new DateTime(1973, 2, 18),
        Isbn="2-444-77777-2",
        Subject=Subjects[1]
      }
    };
  }

Linq中连接的更多相关文章

  1. Linq中的连接(join)

    http://www.cnblogs.com/scottckt/archive/2010/08/11/1797716.html Linq中连接主要有组连接.内连接.左外连接.交叉连接四种.各个用法如下 ...

  2. LINQ中的连接(join)用法示例

    Linq中连接主要有组连接.内连接.左外连接.交叉连接四种.各个用法如下. 1. 组连接 组连接是与分组查询是一样的.即根据分组得到结果. 如下例,根据publisther分组得到结果. 使用组连接的 ...

  3. Linq 中 Join 的用法

    Linq中连接主要有组连接.内连接.左外连接.交叉连接四种.各个用法如下. 注:本文内容主要来自<Linq实战>,本例中用到的对象请见文章底部. 1. 组连接 组连接是与分组查询是一样的. ...

  4. Linq to Entity中连接两个数据库时要注意的问题

    Linq to Entity中连接两个数据库时要注意的问题 今天大学同学问了我一个问题,Linq to Entity中连接两个数据库时,报错“指定的 LINQ 表达式包含对与不同上下文关联的查询的引用 ...

  5. 数据库和linq中的 join(连接)操作

    sql中的连接 sql中的表连接有inner join,left join(left outer join),right join(right outer join),full join(full o ...

  6. linq中怎么实现多条件关联的左右连接

    linq左右连接最重要的是DefaultIfEmpty()这个方法和join之后的表中判断是否( temp != null)null,左右连接其实就是表的位置互换. 1.左连接: && ...

  7. EF Linq中的左连接Left Join查询

    linq中的join是inner join内连接,就是当两个表中有一个表对应的数据没有的时候那个关联就不成立. 比如表A B的数据如下 from a in A join b in B on a.BId ...

  8. LinQ中合并、连接、相交、与非查询

    LinQ中Union合并查询:连接不同的集合,自动过滤相同项:延迟.即是将两个集合进行合并操作,过滤相同的项 var cities = (from p in mylinq.System_Places ...

  9. Linq中关键字的作用及用法

    Linq中关键字的作用及用法 1.All:确定序列中的所有元素是否都满足条件.如果源序列中的每个元素都通过指定谓词中的测试,或者序列为空,则为 true:否则为 false. Demo: 此示例使用 ...

随机推荐

  1. djang系列5.5-- 图书管理系统实例

    一.表格设计 E-R图 分析图 models.py from django.db import models # Create your models here. class Author(model ...

  2. Gogland编译Syncthing!

    说明:我仅仅以这个Syncthing工程为例,来说明如何正确使用Goland编译其他人写的工程,应该具有普遍意义,看懂这篇博客,你想用Gogland去编译其他人的工程,应该不是问题!! Syncthi ...

  3. Aircrack-ng无线破解总结

    过年回来家,奈何没网,实属无奈,只好看破解教程,看能否破出来.于是总结如下 测试环境在linux平台下,我用的是ubuntu环境.ubuntu安装可以直接用sudo apt-get install a ...

  4. objectARX 关于MFC类向导 无法向此非CCmdTarget派生类添加任何命令 的解决方式

    objectARX 关于MFC类向导 无法向此非CCmdTarget派生类添加任何命令  的解决方式 图文By edata ,转载注明出处 http://www.cnblogs.com/edata 1 ...

  5. Getting Started with Elastic Search in .NET

    I have been working on many application during my career.  Many if not all had some searching capabi ...

  6. 【vue】——CDN或全局引入CSS、JS。

    在入口文件index.html中添加 <!DOCTYPE html> <html> <head> <meta charset="utf-8" ...

  7. mysql 多实例

    linux系统下,先用mysql用户帐号的身份建立数据表:/usr/local/webserver/mysql/bin/mysql_install_db --basedir=/usr/local/we ...

  8. python基础之循环

    一.while循环 如果条件成立(true),重复执行相同操作,条件不符合,跳出循环 while   循环条件: 循环操作 (1)while循环示例 例:输入王晓明5门课程的考试成绩,计算平均成绩 i ...

  9. time 模块学习

    前情提要: time模块是经常使用的模块.主要是用来记录时间,以及时间上的相关操作 一:时间戳 1:第一种形式 import time print(time.time()) 从1970 1 1 0:0 ...

  10. Oracle执行SQL语句的过程

    转载至:http://blog.csdn.net/aqszhuaihuai/article/details/7024551 当我们提交一条sql语句时,Oracle会做哪些操作呢? Oracle会为每 ...