c# - 有没有办法可以缓存 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 语句完成整个事情,我将不胜感激。
谢谢。
解决方案
你可以尝试这样的事情:
var employeeWithProject = employees
.Select(e => e.GetProjects().EmployeeProjects.FirstOrDefault(p => p.ProjectId.Equals(guid)))
.FirstOrDefault(x=> x != null);
在这里,您从员工中选择想要的项目,然后获取第一个不为空的项目
推荐阅读
- javascript - jQuery 是否空分离通过 addEventListener 附加的侦听器?
- ios - 无法对 SKPhysicsbody 施加脉冲
- java - 使用 Jackson 将 POJO 序列化为 xml 时删除 xml 包装器
- matplotlib - RuntimeError:动画函数必须返回一系列 Artist 对象
- java - javax.sql.DataSource BeanCurrentlyInCreationException(循环引用?)
- node.js - MySQL函数返回未定义,但确实连接
- java - 我遇到了字符串和整数以及转换 Java 的错误
- php - Illegal Instruction (core dumped) with Tensorflow 1.5
- java - Mokito 不返回我的值实例调用数据库
- html - 如何知道html页面的语言?