SQL自连接查询到LINQ查询

时间:2013-04-15 07:24:26

标签: c# sql linq

我对将SQL查询转换为LINQ感到困惑。任何身体都可以帮助我。 这是我的查询

SELECT x.*
  FROM FilterType x
  JOIN (SELECT t.FilterType
          FROM FilterType t
          where FilterId in (7,15)
      GROUP BY t.FilterType
        HAVING COUNT(t.FilterType) > 1) y ON y.FilterType = x.FilterType

提前致谢。

2 个答案:

答案 0 :(得分:1)

假设您有int[] ids = { 7, 15 }。然后查询将如下所示:

from t in FilterType.Where(x => ids.Contains(x.FilterId))
group t by t.FilterType into g
where g.Count() > 1
from f in g
select f

或者使用方法语法:

FilterType.Where(x => ids.Contains(x.FilterId))
          .GroupBy(t => t.FilterType)
          .Where(g => g.Count() > 1)
          .SelectMany(g => g);

生成的SQL与您的完全不同,但结果应该相同。

答案 1 :(得分:0)

from a in FilterType
join b in
    (
        from x in FilterType
        where (new int[]{7, 15}).Contains(x.FilterID)
        group x by new {x.FilterType} into g
        where g.Count() > 1
        select new {FilterType = g.Key.FilterType}
    ) on a.FilterType equals b.FilterType
select a;