码迷,mamicode.com
首页 > 其他好文 > 详细

LINQ的左连接、右连接、内连接和Lamda表达式实现Left join

时间:2017-04-13 00:57:55      阅读:664      评论:0      收藏:0      [点我收藏+]

标签:color   c99   amd   nal   class   time   detail   结构体类型   from   

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 });

 

LINQ的左连接、右连接、内连接和Lamda表达式实现Left join

标签:color   c99   amd   nal   class   time   detail   结构体类型   from   

原文地址:http://www.cnblogs.com/shiyh/p/6701839.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!