GroupJoin操作:
private void GroupJoinQuery()
{ ///构建数据源
List<UserInfo> users = new List<UserInfo>();
List<RoleInfo> roles = new List<RoleInfo>();
for (int i = 1; i < 10; i++)
{
users.Add(new UserInfo(i,"User0" + i.ToString(),"User0" + i.ToString() + "@web.com",i * 2));
roles.Add(new RoleInfo(i,"RoleName0" + i.ToString()));
}
///查询ID值小于9,且角色包含在roles中的用户
var value = from u in users
where u.ID < 9
join r in roles on u.RoleID equals r.ID into g
select new
{
ID = u.ID,
Username = u.Username,
Email = u.Email,
RoleID = u.RoleID,
Roles = g.ToList()//用ToList()将查询结果转化为List集合
};
///显示查询结果
foreach (var v in value)
{
Response.Write(v.Username + "," + (v.Roles.Count > 0 ? v.Roles[0].RoleName : string.Empty) + "</br>");
}
}