LINQ-使用.Any()保持对象之间的顺序

本文关键字:对象 之间 顺序 使用 Any LINQ- | 更新日期: 2023-09-27 18:19:48

我正在构建一个搜索函数,它需要返回一个按相关性排序的列表。

IList<ProjectDTO> projects = new List<ProjectDTO>();
projects = GetSomeProjects();
List<ProjectDTO> rawSearchResults = new List<ProjectDTO>();
//<snip> - do the various search functions here and write to the rawSearchResults
//now take the raw list of projects and group them into project number and 
//number of search returns.
//we will sort by number of search returns and then last updated date
var orderedProjects = rawSearchResults.GroupBy(x => x.ProjectNbr)
                                      .Select(x => new
                                      {
                                          Count = x.Count(),
                                          ProjectNbr = x.Key,
                                          LastUpdated = x.First().UpdatedDateTime
                                      })
                                      .OrderByDescending(x => x.Count)
                                      .ThenByDescending(x => x.LastUpdated);

到目前为止还不错;"orderedProjects"变量按正确的顺序返回我的列表。但是,下一步我需要整个对象。当我试图查询回原始对象类型时,结果会失去顺序。回想起来,这是有道理的,但我需要找到绕过它的方法

projects = (from p in projects
            where orderedProjects.Any(o => o.ProjectNbr == p.ProjectNbr)
            select p).ToList();

是否有一种LINQ友好的方法来保留上述项目查询中的顺序?

我可以循环浏览orderedProject列表并获取每个项目,但这不是很有效。我也可以在原始orderedProjects查询中重建整个对象,但如果可能的话,我希望避免这种情况。

LINQ-使用.Any()保持对象之间的顺序

您需要用另一种方法:
查询orderedProjects,从projects:中选择相应的项目

var projects = 
    orderedProjects
        .Select(o => projects.SingleOrDefault(p => p.ProjectNbr == o.ProjectNbr))
        .Where(x => x != null) // This is only necessary if there can be
                               // ProjectNbrs in orderedProjects that are not in
                               // projects
        .ToList();

您不应该在中间使用"Select",因为该运算符将对象转换为另一种类型,并且您说您需要原始对象。

var orderedProjects = rawSearchResults.GroupBy(x => x.ProjectNbr)                                      
                                  .OrderByDescending(x => x.Count)
                                  .ThenByDescending(x => x.First().UpdatedDateTime);

它们是按时间顺序来的还是什么的?否则,我敢肯定你希望"ThenByDescending"在最新或最旧的项目更新上执行,比如:

var orderedProjects = rawSearchResults.GroupBy(x => x.ProjectNbr)                                      
                                  .OrderByDescending(x => x.Count)
                                  .ThenByDescending(x => x.Max(p=>p.UpdatedDateTime));