有没有一种方法可以缓存LINQ参数并在以后重用它



有没有一种方法可以缓存LINQ参数并在以后重用它进行优化?

这是我的情况。

public interface IEmployee
{
ProjectCollection GetProjects();
// ...
}
public class ProjectCollection
{
List<Project> EmployeeProjects { get; private set; }
// ...
}
public class Project
{
public Guid ProjectId { get; private set; }
// ...
}

现在,给定一个employees list列表和一个给定的ProjectId(guid(,我需要检索Project对象。

我尝试了两个LINQ语句的组合,一个用于找到合适的员工,另一个用于查找合适的项目但是有没有一种方法可以在一条语句中完成,或者至少可以通过将员工缓存到某个地方来优化它

public Project GetProject(List<IEmployee> employees, Guid id)
{
Project rtn = null;
// Step 1: Retrieve the employee who has the right project.
var employeeWithProject = employees.Where (e => e.GetProjects().EmployeeProjects.Any(p => p.ProjectId.Equals(guid))).FirstOrDefault(); // Note: This retrieves the employee. But I need to cache the part [e.GetProjects().EmployeeProjects] to query it later.
if employeeWithProject != null)
{
// Step 2: Retrieve the project itself.
rtn = employeeWithProject.GetProjects().EmployeeProjects.Where(p => p.ProjectId.Equals(guid)).FirstOrDefault(); // Note: This retrieves the actual project from the previously set employeeWithProject
}
return rtn; // nothing found
}

我真的不喜欢这个解决方案,想知道是否有人能帮我优化它。它基本上在Projectcollection中迭代两次。因此,如果有人能想出一种方法用一个LINQ语句来完成整个事情,我将不胜感激

谢谢。

您可以尝试以下操作:

var employeeWithProject = employees
.Select(e => e.GetProjects().EmployeeProjects.FirstOrDefault(p => p.ProjectId.Equals(guid)))
.FirstOrDefault(x=> x != null);

在这里,你从员工中选择想要的项目,然后得到第一个不是空的项目

SelectMany也可以在这里工作。

static public Project GetProject(List<Employee> employees, Guid id)
=> employees
.SelectMany( e => e.GetProjects()?.EmployeeProjects)
.FirstOrDefault( p => p.ProjectId == id);

最新更新