• Linq中使用Left Join


    准备一些测试数据,如下:

    复制代码
    use Test Createtable Student( ID intidentity(1,1) primarykey, [Name]nvarchar(50) notnull )
    CreateTable Book( ID intidentity(1,1) primarykey, [Name]nvarchar(50)notnull, StudentID intnotnull )
    insertinto Student values('张三') insertinto Student values('李四') insertinto Student values('王五') select*from student
    --张三借的书insertinto Book values('红楼',1) insertinto Book values('大话红楼',1)
    --李四借的书insertinto Book values('三国',2)
    --王五没借书--一本错误的记录insertinto Book values('错误时怎样练成的',111)
    --左连接select s.name,b.name from student as s leftjoin Book as b on s.id=b.studentid
    --右连接select s.name,b.name from student as s rightjoin Book as b on s.id=b.studentid
    复制代码

    要用Linq实现左连接,写法如下

    复制代码
    DataClasses1DataContext db =new DataClasses1DataContext(); var leftJoinSql = from student in db.Student join book in db.Book on student.ID equals book.StudentID into temp from tt in temp.DefaultIfEmpty() select new { sname= student.Name, bname = tt==null?"":tt.Name//这里主要第二个集合有可能为空。需要判断 };
    复制代码

    用Linq实现右连接,写法如下

    复制代码
    DataClasses1DataContext db=new DataClasses1DataContext(); var rightJoinSql = from book in db.Book join stu in db.Student on book.StudentID equals stu.ID into joinTemp from tmp in joinTemp.DefaultIfEmpty() select new { sname=tmp==null?"":tmp.Name, bname=book.Name
    };
    复制代码

    参考资料:http://developer.51cto.com/art/200909/152189.htm

    http://hi.baidu.com/thinsoft/blog/item/83fb1e9089cc7186a877a4b1.html

    http://apps.hi.baidu.com/share/detail/12540006

    http://www.winu.cn/space-14160-do-blog-id-25172.html

  • 相关阅读:
    LightOJ 1422 Halloween Costumes(区间dp)
    zoj 3537 Cake(区间dp)
    POJ 2955 Brackets(区间dp)
    HDU 1058 Humble Numbers(dp)
    uva 10934 Dropping water balloons(转载)
    树形dp
    Manacher算法求回文半径
    poj-1236.network of schools(强连通分量 + 图的入度出度)
    hdu-2255.奔小康赚大钱(最大权二分匹配)
    poj-2289.jamies contact groups(二分答案 + 二分多重匹配)
  • 原文地址:https://www.cnblogs.com/zcm123/p/3118634.html
Copyright © 2020-2023  润新知