首页 > 解决方案 > 有没有办法可以缓存 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; }
    // ...
}

现在给定一个员工列表和一个给定的 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 语句完成整个事情,我将不胜感激。

谢谢。

标签: c#linq

解决方案


你可以尝试这样的事情:

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

在这里,您从员工中选择想要的项目,然后获取第一个不为空的项目


推荐阅读