2012-02-09 173 views
0

我想通過Guid(最常用的)來訂購一堆記錄,然後按這一列進行分組,並採用前3個最常用的Guid。Linq to Entities - GroupBy

IList<Records> dbobjs = dbContext.Records 
     .OrderByDescending(t => t.Id) 
     .GroupBy(t => t.Id) 
     .Take(3) 
     .ToList(); 

這不工作......我做錯了什麼?它的名言:

Cannot implicitly convert type 'System.Collections.Generic.List<System.Linq.IGrouping<System.Guid,DataAccessLayer.Records>>' to 'System.Collections.Generic.IList<DataAccessLayer.Records>'. An explicit conversion exists (are you missing a cast?)

感謝

+0

Id不應該是唯一的嗎?因此'GroupBy'沒有什麼意義,或者我錯過了什麼? – 2012-02-09 19:34:00

回答

10

您的查詢正在返回記錄分組 - 但您只是試圖將查詢結果分配給IList<Records>。那麼你是否對前三個實際記錄感興趣?如果是這樣,你可以使用:

IList<Records> dbobjs = dbContext.Records 
     .OrderByDescending(t => t.Id) 
     .GroupBy(t => t.Id) 
     .SelectMany(group => group) // Flatten again 
     .Take(3) 
     .ToList(); 

......但在這一點上,目前尚不清楚分組的重點是什麼。如果您想選擇只是一個記錄每個ID,你可以使用:

IList<Records> dbobjs = dbContext.Records 
     .OrderByDescending(t => t.Id) 
     .GroupBy(t => t.Id) 
     .Take(3) 
     .Select(group => group.First()) 
     .ToList(); 

編輯:如果你只需要的GUID,你會使用:

IList<Guid> guids = dbContext.Records 
     .OrderByDescending(t => t.Id) 
     .GroupBy(t => t.Id) 
     .Take(3) 
     .Select(group => group.Key) 
     .ToList(); 
+0

「Id」列是我需要的。所以一個IList <>包含3個Guid's – Nugs 2012-02-09 19:31:42

+0

@Nugs:如果你只需要GUID,你爲什麼要分配給IList ?將編輯。 – 2012-02-09 19:33:13

+0

謝謝你的幫助!這是訣竅。我讚賞額外的幫助... – Nugs 2012-02-09 19:34:52

3

正如錯誤中明確規定,GroupBy返回一組分組,而不是一組記錄。

+0

好吧,那麼應該如何施展才能獲得前3名Guid? – Nugs 2012-02-09 19:26:44

-1

如果執行此比結果不會是IList。 試試這個,你會看到:

var dbobjs = dbContext.Records 
     .OrderByDescending(t => t.Id) 
     .GroupBy(t => t.Id) 
     .Take(3) 
     .ToList(); 

移動cursur在Visual Studio中的var關鍵字。 ;)