c# - 在Linq中分组并拥有两项计数

时间:2015-11-18 16:00:43

标签: c# linq group-by having

如何在C#中用Linq编写跟随查询?

SELECT MAX(A2.LINHA_PLANILHA)
FROM MD_IMP_FORCA_VENDA_DADOS_A2 A2
WHERE A2.LINHA <> '0' 
    AND TRIM(A2.SETORES) IS NOT NULL
    AND A2.LINHA_PLANILHA <> 1
    AND USUARIO = V_USUARIO
GROUP BY A2.LINHA, A2.BRICK
HAVING COUNT(A2.BRICK) > 1 AND COUNT(DISTINCT A2.SETORES) > 1;

我想这样做:

var result = from r in dataTable.AsEnumerable() 
where r.Field<string>(1) != "0" 
    && r.Field<string>(2).Trim() != null 
    && r.Field<Int32>(0) != 1 
group r by new {Linha = r.Field<string>(1), Brick = r.Field<string>(3) } into temp 
where temp.Count() > 1 
select new { MaxLinha = (from r2 in temp select r2.Field<Int32>(0)).Max()}; 

但我不知道如何在Linq查询中放置两个COUNTS of HAVING子句。

任何帮助都将不胜感激。

由于

扎戈

1 个答案:

答案 0 :(得分:1)

也许:

var query = db.MD_IMP_FORCA_VENDA_DADOS_A2
    .Where(x => x.LINHA  != "0" 
             && x.SETORES != null 
             && x.SETORES.Trim() != ""
             && x.LINHA_PLANILHA <> 1
             && x.USUARIO = x.V_USUARIO
    ) 
    .GroupBy(x => new { x.LINHA, x.BRICK })
    .Where(g => g.Count() > 1 && g.Select(x => x.SETORES).Distinct().Count() > 1)
    .Select(g => g.Max(x => x.LINHA_PLANILHA));