C# 使用linq进行分组以返回不正确的结果
在我最近的应用程序中,我有一个C# 使用linq进行分组以返回不正确的结果,c#,linq,group-by,linq-to-entities,C#,Linq,Group By,Linq To Entities,在我最近的应用程序中,我有一个文档实体,该文档可以从一个用户引用到另一个用户,每组用户也有一个文档站;这些是指登录的DocumentStationHistory表格: 现在,我想首先使用EF代码列出DocumentStationHistory表中的所有最后一个文档引用到Dictionary(分组依据documentId)。 所以我写了这些方法: public Dictionary<int, DocumentStationHistory> GetLastDocumentStation
文档
实体,该文档可以从一个用户引用到另一个用户,每组用户也有一个文档站
;这些是指登录的DocumentStationHistory
表格:
现在,我想首先使用EF代码列出DocumentStationHistory
表中的所有最后一个文档引用到Dictionary
(分组依据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;
}
}
公共字典GetLastDocumentStationHistoryListOfDocuments(字符串标准)
{
字典结果=新字典();
使用(IUnitOfWork uow=new MyContext())
{
DocumentStationHistoryRepository repository=新DocumentStationHistoryRepository(uow);
结果=repository.All()。
包括(x=>x.DocumentStation)。
其中(条件,新对象[]{})。
OrderBy(d=>d.DocumentId)。
OrderBy(d=>d.DocumentStationHistoryId)。
GroupBy(g=>(int)g.DocumentId)。
ToDictionary(g=>(int)g.Key,g=>g.LastOrDefault());
返回结果;
}
}
它返回一个字典,但结果不正确,它不返回每个文档的最后一次引用,也不返回DocumentStation
导航属性,结果为null
。
我的错误在哪里?订购时有两个问题:
- 您使用了两次
,这几乎肯定不会达到您认为的效果。您通常应该使用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
的另一种方法是使用OrderByDescending
和然后bydescending
,然后再使用首先
恐怕我不知道
DocumentStation
包含部分。谢谢,分组问题已经解决,但导航属性仍然为空。@Masoud:可能值得将其拆分为一个单独的问题。。。如果可以,最好删除分组部分。(如果不分组,它是否保留导航属性?)。