2014-02-24 25 views
0

我使用Linq(連同EF)來訪問我的數據庫。我有對象「工作」,其中包含幾個屬性,其中一些是「複雜」。我的目標是按這些屬性對作業進行分組,併爲每個組計數。關於Linq分組的另一個問題

這裏我對象(簡體):

public class Job 
{ 
    [Key] 
    public int Id 
    { 
     get; 
     set; 
    } 


    [Required] 
    public Salary Salary 
    { 
     get; 
     set; 
    } 


    [Required] 
    public ICollection<Category> Categories 
    { 
     get; 
     set; 
    }  
} 

「類別」 是一個複雜的類,並且看起來是這樣的:

public class Category 
{ 
    [Key] 
    public int Id 
    { 
     get; 
     set; 
    } 

    public Industry Industry //Example: Software 
    { 
     get; 
     set; 
    } 


    public Field Field //Example: .NET 
    { 
     get; 
     set; 
    } 


    public Position Position //Example: Developer 
    { 
     get; 
     set; 
    } 
} 

行業,領域,職位和薪資類僅包含「INT 「id和」字符串「名稱。

我需要根據行業,領域,職位和薪資對作業列表進行分組,並獲得每個組的計數。這是我現在這樣做:

var IndustryGroupsQuery = from t in Jobs.SelectMany(p => p.Categories) 
              group t by new { t.Industry} into g 
              select new 
              { 
               Tag = g.Key.Industry, 
               Count = g.Count() 
              }; 

var FieldsGroupsQuery = from t in Jobs.SelectMany(p => p.Categories) 
              group t by new { t.Field} into g 
              select new 
              { 
               Tag = g.Key.Field, 
               Count = g.Count() 
              }; 

var PositionsGroupsQuery = from t in Jobs.SelectMany(p => p.Categories) 
              group t by new { t.Position} into g 
              select new 
              { 
               Tag = g.Key.Position, 
               Count = g.Count() 
              }; 

Jobs.GroupBy(job => job.Salary) 
         .Select(group => new 
         { 
          Tag = group.Key, 
          Count = group.Count() 
         })) 

這是工作正常,但我想知道是否有可能以某種方式提高其性能。第一季度:我認爲,這可能是一個單一的查詢將執行更好的四個。是否有可能將這些查詢合併爲一個查詢?

問題二:當我要求Linq按「工業」分組時,它究竟能夠區分一個行業與另一個行業?它隱式比較記錄的關鍵?如果我明確告訴linq要分組的屬性(例如「id」),它會更快嗎?

謝謝!

回答

0

回答以相反的順序:

Q2:
當通過一個對象,而不是基類型的基團,它使用標準的相等比較器(物鏡X == OBJ Y),其執行一個簡單的參考比較( http://msdn.microsoft.com/en-us/library/bsc2ak47(v=vs.110).aspx)。如果適合,它的工作原理,否則,你可以實現自定義相等比較器(How to implement IEqualityComparer to return distinct values?

Q1:
如果你想組的子組,那麼您可以在單個查詢做到這一點。如果你只是想每個人的數量,那麼你正在做的是正確的方式。

+0

如果查詢在數據庫上運行,它如何通過引用進行比較? – Illidan

0

您可以使用條件爲GROUP BY

您可以定義一個變量來告訴查詢哪個列用於分組。您可以爲GROUP BY列定義一個ENUM。

int groupByCol = 1; //Change the value of this field according to the field you want to group by 

var GenericGroupsQuery = from t in Jobs           
          group t by new { GroupCol = (groupByCol == 1 ? t.Industry:(groupByCol == 2 ? t.Field:(groupByCol == 3 ? t.Position : t.Job)))} into g 
          select new 
          { 
           Tag = g.Key, 
           Count = g.Count() 
          };