http://www.cnblogs.com/scottckt/archive/2010/08/11/1797716.html

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中的连接(join)的更多相关文章

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

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

  2. Linq 中的 left join

    Linq 中的 left join 表A User: 表B UserType: Linq: from t in UserType join u in User on t.typeId equal u. ...

  3. Linq中使用Left Join

    use Test Create table Student( ID ,) primary key, ) not null ) Create Table Book( ID ,) primary key, ...

  4. [转]Linq中使用Left Join

    本文转自:http://www.cnblogs.com/xinjian/archive/2010/11/17/1879959.html use Test Create table Student( I ...

  5. Linq中使用Left Join rught join

    准备一些测试数据,如下: use Test Create table Student( ID int identity(1,1) primary key, [Name] nvarchar(50) no ...

  6. Linq中使用Left Join 和 Right Join

    原文地址:http://www.cnblogs.com/xinjian/archive/2010/11/17/1879959.html 准备一些测试数据,如下: use Test Create tab ...

  7. Linq 中 表连接查询

    public void Test(){ var query = from a in A join b in B on A.Id equals B.Id into c from d in c.Defau ...

  8. linq中如何在join中指定多个条件

    public ActionResult Edit(int id) { using (DataContext db = new DataContext(ConfigurationManager.Conn ...

  9. Linq中的left join

    left join var custs = from c in db.T_Customer join u in db.Sys_User on c.OwnerId equals u.Id into te ...

随机推荐

  1. how to use fiddler and wireshark to decrypt ssl

    原文地址: http://security14.blogspot.jp/2010/07/how-to-use-fiddler-and-wireshark-to.html Requirements2 C ...

  2. ios 获得通讯录中联系人的所有属性 亲测,可行 兼容io6 和 ios 7

    //获取通讯录中的所有属性,并存储在 textView 中,已检验,切实可行.兼容io6 和 ios 7 ,而且ios7还没有权限确认提示. -(void)getAddressBook { ABAdd ...

  3. pycurl post

    pc = pycurl.Curl() pc.setopt(pycurl.POST, 1) pc.setopt(pycurl.URL, 'http://192.168.0.25:/Image') #pc ...

  4. 从源码角度一步一步来修改PreferenceActivity界面

         PreferenceActivity给我们封装好了一个数据存储对象,我们只需要在xml文件中写上控件即可完成简单的设置界面.但是系统提供的设置界面十分的简陋,要想做的好看必须要自己来进行修改 ...

  5. jquery获取table,遍历输出tr中各个td的内容(转载)

    首先,依赖jquery.. 1 $('#btntb').click(function(){ 2 $('#tab tr').each(function(i){ // 遍历 tr 3 $(this).ch ...

  6. CSS3 Flex布局整理(一)

    一.说明 1.在以往的布局方案中,都是基于盒装模型,依赖display属性+position属性+float属性等. 他对于那些特殊布局非常不方便,比如,垂直居中等. 并且不同浏览器的盒模型还有些差异 ...

  7. Java&C#语法差别

      Java C# 主类名与文件名 必须一致 可以不一致 命名空间导入方式 import关键字 using关键字 常量 final关键字 Const关键字 基本数据类型 C#中有无符号数,Java没有 ...

  8. protobuf标准消息方法

    protobuf标准消息方法 1.标准消息方法 每个消息类包含一些其他方法允许你检查和控制整个消息,包括: · IsInitialized() :检查是否所有必须(required)字段都已经被赋值了 ...

  9. Django静态文件的加载以及STATIC_URL、 STATIC_ROOT 、STATICFILES_DIRS的区别

    Djangon生产环境静态资源的处理 Django 关闭DEBUG模式后,就相当于是生产环境了. Django框架一旦作为生产环境,它的静态文件访问接口就不应该从Django框架中走,必须在Djang ...

  10. c++流缓冲学习---rdbuf()

    我们使用STL编程的时候有时候会想到把一个流对象指向的内容用另一个流对象来输出,比如想把一个文件的内容输出到显示器上,我们可以用简单的两行代码就可以完成: ifstream infile(" ...