至於我也明白了,你要顯示的JobsCount &天計算每個人,每個都具有不同的一組標題的,在這種情況下,試試這個: -
var result = tstPData.GroupBy(x => new { x.PersonnelId, x.Name , x.Position })
.Select(x => new
{
PersonnelId = x.Key.PersonnelId,
Name = x.Key.Name,
Position = x.Key.Position ,
JobCount = x.Count(),
DaysCount = x.Count()
});
最後,您可以枚舉結果並分配給您的模型。
更新:根據您的型號
我已創建自定義的數據對象: -
List<PersonnelStats> persons = new List<PersonnelStats>
{
//Same Job for Alex but different date
new PersonnelStats { Name="Alex", Position="Dev", JobId= new Guid("11223344-5566-7788-99AA-BBCCDDEEFF00"), PersonnelId = new Guid("11223344-5566-7788-99AA-BBCCDDEEFF00"), Date= new DateTime(2015,03,12)},
new PersonnelStats { Name="Alex", Position="Dev", JobId= new Guid("11223344-5566-7788-99AA-BBCCDDEEFF00"), PersonnelId = new Guid("11223344-5566-7788-99AA-BBCCDDEEFF00"), Date= new DateTime(2015,03,15)},
//Two jobs for Mary
new PersonnelStats { Name="Mary", Position="App", JobId= new Guid("11229944-2356-7788-99AA-BBCCDDEEFF00"), PersonnelId = new Guid("11223344-1567-6565-99AA-BBCCDDEEFF00"), Date= new DateTime(2015,03,13)},
new PersonnelStats { Name="Mary", Position="App", JobId= new Guid("11229944-3445-7788-99AA-BBCCDDEEFF00"), PersonnelId = new Guid("11223344-1567-6565-99AA-BBCCDDEEFF00"), Date= new DateTime(2015,03,13)},
//Two jobs for Mark with 1 job being at different dates.
new PersonnelStats { Name="Mark", Position="Test", JobId= new Guid("11223344-7879-2344-99AA-BBCCDDEEFF00"), PersonnelId = new Guid("11223344-2245-4343-99AA-BBCCDDEEFF00"), Date= new DateTime(2015,03,17)},
new PersonnelStats { Name="Mark", Position="Test", JobId= new Guid("11223344-5522-2344-99AA-BBCCDDEEFF00"), PersonnelId = new Guid("11223344-2245-4343-99AA-BBCCDDEEFF00"), Date= new DateTime(2015,03,17)},
new PersonnelStats { Name="Mark", Position="Test", JobId= new Guid("11223344-5522-2344-99AA-BBCCDDEEFF00"), PersonnelId = new Guid("11223344-2245-4343-99AA-BBCCDDEEFF00"), Date= new DateTime(2015,03,18)},
};
這是給我所需要的輸出代碼: -
var result = persons.GroupBy(x => new { x.PersonnelId, x.Name, x.Position })
.Select(x => new
{
PersonnelId = x.Key.PersonnelId,
Name = x.Key.Name,
Position = x.Key.Position,
JobCount = x.Select(z => z.JobId).Distinct().Count(),
DaysCount = x.Select(z => z.Date.Date).Distinct().Count()
});
是的,你很瞭解我的觀點。但是,這行「x.Count(z => z.JobId),」給出錯誤「無法將System.Guid轉換爲Bool,並且x.Count(z => z.Date.Date)表示無法將System.Date轉換爲bool。 – immirza
Rahul,感謝您的評論。所以你的意思是說我需要寫兩個分離組,比如新的{x.PersonnelId,x.Name,x.Position,x.JobId}和新的{x.PersonnelId,x。名稱,x.Position,x.Date}並且比個人計數更多?我不確定您的評論。請根據您的評論更新您的代碼,如果可能的話 – immirza
Rahul,var result = tstPData.GroupBy(x => new {x.PersonnelId,x.Name,x.Position}) 。選擇(X =>新 { PersonnelId = x.Key.PersonnelId, 名稱= x.Key.Name, 位置= x.Key.Position , JobCount = x.GroupBy(y => new {y.PersonnelId, y.JobId})。Select(y => y.Distinct()。Count()), DaysCount = x.GroupBy(y => new {y.PersonnelId,y.Date})。Select(y => y .Distinct()。Count()) })。ToList();「 – immirza