zoukankan      html  css  js  c++  java
  • LINQ的左连接、右连接、内连接和Lamda表达式实现Left join

    1、左连接:

    var LeftJoin = from t1 in l1
    join t2 in l2
    on t1.ID equals t2.ID into Joinedt12
    from t3 in Joinedt12.DefaultIfEmpty()
    select new                        
    {
    Name = t1.Name,
    Age=t2.Age                      
    };

     

    2、右连接:

    var RightJoin = from t2 in l2
    join t1in l1
    on t2.ID equals t1.ID into joint12
    from t3 in joint12.DefaultIfEmpty()
    select new                          
    {
    Name = t1.Name,
    Age=t2.Age  

    };

     

    3、内连接:

     var query = from t1 in l1
                     join t2 in l2
                     on t1.ID equals t2.ID

                     select new t3
                     {
                        USER_ID = t1.USER_ID,
                        USER_NAME = t1.USER_NAME,
                        USER_PASSWORD = t1.USER_PASSWORD,

                     };

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

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

    Lamda表达式实现Left join

    public class AnalysisPlayer
    {
            /// <summary>
            /// 玩家名称
            /// </summary>
            public string PlayerName { get; set; }
            /// <summary>
            /// 玩家账号
            /// </summary>
            public string Account { get; set; }
            /// <summary>
            /// 注册时间
            /// </summary>
            public DateTime RegTime { get; set; }
            /// <summary>
            /// 充值总数
            /// </summary>
            public int Points { get; set; }
    }
    ------解决方案--------------------
    var query = User.GroupJoin(Charge, u => u.Account, c => c.Account, (u, c) => new { u, c })
    .Select(data => new AnalysisPlayer { Account = data.u.Account, PlayerName = data.u.Name,  
    RegTime = data.u.CreateTime ?? DateTime.Now, Points =data.c==null?0:data.c.Points });
  • 相关阅读:
    HDU 4031 Attack(离线+线段树)(The 36th ACM/ICPC Asia Regional Chengdu Site —— Online Contest)
    BZOJ 1010 玩具装箱toy(四边形不等式优化DP)(HNOI 2008)
    分布式事务二阶提交DTS系统
    flume原理及代码实现
    Liferay JSP Tag Libraries介绍
    如何用maven tycho构建自己的Eclipse RCP应用
    如何合并两个git commit
    推荐一个好用的git图形化工具
    git gc干了啥
    如何把VS Code的Language Server Protocol整合到Eclipse中来
  • 原文地址:https://www.cnblogs.com/shiyh/p/6701839.html
Copyright © 2011-2022 走看看