2013-07-08 123 views
0

在我最近的应用程序中,我有一个Document实体,并且此文档可以将用户引用到另一个用户,每个用户组也有DocumentStation;这是指记录在DocumentStationHistory表: enter image description here使用LINQ分组返回非正确的结果

现在,我要列出所有最后一份文件指的是包厢在DocumentStationHistory表到Dictionary使用EF代码第一个(组由documentId)。 所以我写了这些方法:

public Dictionary<int, DocumentStationHistory> GetLastDocumentStationHistoryListOfDocuments(string criteria) 
{ 
     Dictionary<int, DocumentStationHistory> result = new Dictionary<int, DocumentStationHistory>(); 
     using (IUnitOfWork uow = new MyContext()) 
     { 
      DocumentStationHistoryRepository repository = new DocumentStationHistoryRepository(uow); 
      result = repository.All(). 
       Include(x => x.DocumentStation). 
       Where(criteria,new object[]{}). 
       OrderBy(d=>d.DocumentId). 
       OrderBy(d=>d.DocumentStationHistoryId). 
       GroupBy(g => (int)g.DocumentId). 
       ToDictionary(g => (int)g.Key, g => g.LastOrDefault()); 
      return result; 
     } 
} 

它返回一个字典,但结果是不正确的,它不会返回最后是指每个文档的,也DocumentStation导航属性,在结果是null。 我的错误在哪里?对于排序

回答

2

两个问题:

  • 您使用OrderBy两次,这几乎可以肯定不会做你认为它。你通常应该使用OrderBy其次ThenBy
  • 我不相信GroupBy是保证序列的其余部分的顺序。你应该在责令分组:

    result = service.All() 
         .Include(x => x.DocumentStation) 
         .Where(criteria, new object[]{}) 
         .GroupBy(g => (int)g.DocumentId) 
         .ToDictionary(g => (int)g.Key, 
             g => g.OrderBy(d => d.DocumentId) 
              .ThenBy(d => d.DocumentStationHistoryId) 
              .Last()); 
    

(有没有必要使用LastOrDefault - 有至少一个元素是,否则就不会有一组)。

顺便说一句,使用Last的另一种方法是使用OrderByDescendingThenByDescending,然后使用First

我不知道DocumentStation包含部分,恐怕。

+0

谢谢,小组按问题解决,但导航属性为空。 – Masoud

+0

@Masoud:可能值得把它分成单独的问题......如果可以的话,理想情况下已经移除了分组部分。 (如果你*不*组,它是否保留导航属性?) –

+0

是的,如果我不分组,它保持导航属性。 – Masoud