我使用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」),它會更快嗎?
謝謝!
如果查詢在數據庫上運行,它如何通過引用進行比較? – Illidan