2012-02-09 175 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关键字。 ;)