linq 之左连接

2年前 (2022) 程序员胖胖胖虎阿
180 0 0

 

List<ArticleModel> articleList = articleRepository.GetAllArticle();
List<UsersModel> userList = usersRepository.GetAllUsers();

//用户表左连接文章表
var usersLeftJoin = (from u in userList
join a in articleList
on u.Id equals a.Author into users
from us in users.DefaultIfEmpty()
select new
{
author = us == null ? "" : us.Author.ToString(),
name = u.Name.Trim()
}).ToList();

//要避免这种写法,这种写法查出来的数据实际上相当于连接
var usersLeftJoin1 = (from u in userList
join a in articleList
on u.Id equals a.Author into users
from us in users
select new
{
author = us.Author,
name = u.Name.Trim()
}).ToList();

//文章表左连接用户表
var articleLeftJoin = (from a in articleList
join u in userList
on a.Author equals u.Id into users
from us in users.DefaultIfEmpty()
select new
{
title = a.Title.Trim(),
name = us == null ? "" : us.Name.Trim(),
author = a.Author
}).ToList();

//要避免这种写法,这种写法查出来的数据实际上相当于连接
var articleLeftJoin1 = (from a in articleList
join u in userList
on a.Author equals u.Id into users
from us in users
select new
{
name = us.Name.Trim(),
author = a.Author
}).ToList();

//用户表连接文章表
var result = (from a in articleList
from u in userList
where a.Author == u.Id
select new
{
name = u.Name,
author = a.Author
}).ToList();

版权声明:程序员胖胖胖虎阿 发表于 2022年10月5日 上午10:00。
转载请注明:linq 之左连接 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...