2011-06-24 3 views
0

を向上させることができます 私のテーブル構造は、私がentityTypeとステータスによって総コメントをカウントする必要がは、どのように私はこのクエリを向上させることができますどのようにこのLinqToEntities GROUPBY照会

entityType | status | entityTypeId | empresaId 
    E   0   5    2 
    S   1   5    2 
    S   2   6    1 

(ちょうど関連する列を示す)されます。これは私の現在のクエリであり、うまくいきますが、可能であれば1つのクエリで行いたいので、2 las foreachの外観を改善することができます。

public List<Tuple<int, int, string>> GetCountByStatus(int? empresaId) 
     { 
      //Tuple T1 status int code, T2 int count, T3 string type (E/S) 
      List<Tuple<int,int,string>> r = new List<Tuple<int,int,string>>(); 

      var eq = from c in dbContext.Comentarios 
         .Where(c => c.entityType == "E" 
          && (empresaId.HasValue ? c.empresaId == empresaId.Value : true)) 
        select c; 

      var eCount = eq.GroupBy(c => c.status) 
       .Select(gc => new { status = gc.Key, count = gc.Count()}); 

      var sq = from c in dbContext.Comentarios 
         .Where(c => c.entityType == "S" && 
          (empresaId.HasValue ? c.empresaId == empresaId.Value : true)) 
        select c; 

      var sCount = sq.GroupBy(c => c.status) 
       .Select(gc => new { status = gc.Key, count = gc.Count() }); 

      foreach (var item in eCount) 
      { 
       r.Add(new Tuple<int,int,string>(item.status, item.count,"E")); 
      } 
      foreach (var item in sCount) 
      { 
       r.Add(new Tuple<int, int, string>(item.status, item.count, "S")); 
      } 

      return r; 
     } 

答えて

1

は、ここでそれを行うための良い方法です。

  var eCount = (from c in dbContext.Comentarios 
         group c by new 
         { 
          statust = c.EntityType == "E" 
          && (empresaId.HasValue ? c.EmpresaId == empresaId.Value : true) 
         } into g 
         where (bool)g.Key.statust == true 
         select new 
         { 
          status = g.Key, 
          Count = g.Count() 
         });