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