将SQL中的条件连接转换为Linq

时间:2016-11-22 11:52:48

标签: c# sql-server linq

我在SQL中有一个看似简单的查询:

SELECT table1.Id, count(table2.col) AS OrderCol
FROM table1
LEFT JOIN table2 ON table1.Id = table2.Id
LEFT JOIN table3 ON table2.Id = table3.Id AND table2.condition = 3 //some integer value
GROUP BY table1.Id
ORDER BY count(table2.col) DESC

加入中出现AND子句时,我不确定如何将其转换为LINQ ...

如何实现它?

2 个答案:

答案 0 :(得分:1)

它类似于:

from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}

答案 1 :(得分:-1)

试试这个:

var answer = (from t1 in table1
             join t2 in table2 on t1.Id equals t2.Id into subData1
             from t2sub in subData1.DefaultIfEmpty()
             join t3 in table3 on new { Id = t2sub == null ? 0 : t2sub.Id, condition = t2sub == null ? 0 : t2sub.condition } equals new { t3.Id, condition = 3 } into subData
             from t3sub in subData.DefaultIfEmpty()
             group new { t1, t2sub } by t1.Id into subGroup
             orderby subGroup.Count(x => x.t2sub != null) descending 
             select new {
                 Id = subGroup.Key,
                 OrderCol = subGroup.Count(x => x.t2sub != null)
             }).ToList();