C# 将两个查询简化为具有相同类型linq的查询
我有以下代码:C# 将两个查询简化为具有相同类型linq的查询,c#,sql,asp.net,linq,C#,Sql,Asp.net,Linq,我有以下代码: var commentData = from o in quack.BlogComments join u in quack.AdminUsers on o.UserId equals u.AdminUserId where blogid == o.BlogId select new {
var commentData = from o in quack.BlogComments
join u in quack.AdminUsers
on o.UserId equals u.AdminUserId
where blogid == o.BlogId
select new
{
o.Comment,
o.CommentDate,
u.FirstName,
u.LastName
};
var commentData2 = from o in quack.BlogComments
join u in quack.RegularUsers
on o.UserId equals u.RegularUserId
where blogid == o.BlogId
select new
{
o.Comment,
o.CommentDate,
u.FirstName,
u.LastName
};
var l = commentData.ToList();
l.AddRange(commentData2);
正如您在上面看到的,我正在对数据库执行两个不同的查询,然后将它们添加到一起,生成一个列表,用于网格视图
我想要的是只对数据库使用一个查询,并将结果合并为其中两个表
我怎么做?是否可以使用多个联接?您应该使用
Concat
:
var commentData = (from o in quack.BlogComments
join u in quack.AdminUsers
on o.UserId equals u.AdminUserId
where blogid == o.BlogId
select new
{
o.Comment,
o.CommentDate,
u.FirstName,
u.LastName
}).Concat(from o in quack.BlogComments
join u in quack.RegularUsers
on o.UserId equals u.RegularUserId
where blogid == o.BlogId
select new
{
o.Comment,
o.CommentDate,
u.FirstName,
u.LastName
});
var l = commentData.ToList();
在没有嵌套查询的情况下编写
var l=commentData.Concat(commentData2.ToList()
更有意义吗?我们还很高兴地注意到,Lint-to-Sql将能够与UNION
形成一个Sql查询,从而实现到数据库的一次往返。是的,将给出完全相同的结果。@MarcinJuraszek这还会导致到数据库的两个不同查询吗?@IlyaIvanov所以UNION将导致两个表相互添加?@gameon否,它应该只是一个查询Concat
将在生成的SQL中转换为UNION ALL
。