2011-06-24 126 views
0

如何提高這個查詢: 我的表結構(只顯示相關列)我怎樣才能改善這種LinqToEntities GROUPBY查詢

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

我需要通過計數和的EntityType狀態總的意見。這是我當前的查詢,它運作良好,但如果可能的話,想要在一個查詢中做doit,而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() 
         }); 
相關問題