C#在LINQ中左联接 [英] C# Left join in LINQ
本文介绍了C#在LINQ中左联接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
不确定如何将以下sql转换为LINQ表达式.我的数据库确实使用了引用完整性,并且表Content与表Content_Training的关系是一对多的(例如:1个内容可以具有许多content_trainings).
Not sure how to convert the following sql into a LINQ expression. My db does use referential integrity and table Content is related to table Content_Training in a 1 to many relationship (ex: 1 content can have many content_trainings).
select c.ContentId, c.Name, ct.TrainingTypeId
from dbo.Content c left join dbo.ContentTraining ct on c.ContentId = ct.ContentId
where c.ExpirationDate is not null
order by ct.TrainingTypeId, c.Name
我已经尝试过了,这似乎行得通.但是,我不确定"let"关键字的用法.
I have tried this, which seems to work. However, I am not certain about the usage of the "let" keyword.
var data = (from c in context.Contents
let ct = ( from t in context.Content_Training where t.ContentId == c.ContentId
select new { t.TrainingTypeId } ).FirstOrDefault()
where c.ExpirationDate.HasValue
orderby ct.TrainingTypeId, c.Name
select new { c.ContentId, c.Name, ct.TrainingTypeId } ).ToList();
推荐答案
对于左联接,您需要使用DefaultIfEmpty()
For left join, you need to use DefaultIfEmpty()
您的查询应与此类似:
var query = from c in Content
join ct in ContentTraining
on c.ContentId equals ct.ContentId into g
from ct in g.DefaultIfEmpty()
where c.ExpirationDate != null
select new
{
c.ContentId,
c.Name,
ct.TrainingTypeId
}).ToList();
请参考 linq中的左外部联接
和
http://msdn.microsoft.com/en-us/library/bb397895.aspx
这篇关于C#在LINQ中左联接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文