C# 是否有一种方法可以缓存LINQ参数并在以后重用它?
有没有一种方法可以缓存LINQ参数并在以后重用它进行优化 这是我的情况C# 是否有一种方法可以缓存LINQ参数并在以后重用它?,c#,linq,C#,Linq,有没有一种方法可以缓存LINQ参数并在以后重用它进行优化 这是我的情况 public interface IEmployee { ProjectCollection GetProjects(); // ... } public class ProjectCollection { List<Project> EmployeeProjects { get; private set; } // ... } public class Project {
public interface IEmployee
{
ProjectCollection GetProjects();
// ...
}
public class ProjectCollection
{
List<Project> EmployeeProjects { get; private set; }
// ...
}
public class Project
{
public Guid ProjectId { get; private set; }
// ...
}
公共接口IEEmployee
{
ProjectCollection GetProjects();
// ...
}
公共类项目集合
{
列出EmployeeProjects{get;private set;}
// ...
}
公共类项目
{
公共Guid项目ID{get;private set;}
// ...
}
现在给定一个员工列表和一个给定的ProjectId(guid),我需要检索项目对象
我尝试了两种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
}
公共项目GetProject(列出员工,Guid id)
{
项目rtn=null;
//步骤1:检索拥有正确项目的员工。
var employeeWithProject=employees.Where(e=>e.GetProjects().EmployeeProjects.Any(p=>p.projectd.Equals(guid))).FirstOrDefault();//注意:这将检索员工。但我需要缓存部分[e.GetProjects().EmployeeProjects],以便稍后查询。
如果employeeWithProject!=空)
{
//步骤2:检索项目本身。
rtn=employeeWithProject.GetProjects().EmployeeProjects.Where(p=>p.ProjectId.Equals(guid)).FirstOrDefault();//注意:这将从以前设置的employeeWithProject中检索实际项目
}
return rtn;//未找到任何内容
}
我真的不喜欢这个解决方案,不知道是否有人能帮我优化它。它基本上在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);
静态公共项目GetProject(列出员工,Guid id)
=>员工
.SelectMany(e=>e.GetProjects()?.EmployeeProjects)
.FirstOrDefault(p=>p.ProjectId==id);
工作正常。谢谢。感谢您分享此解决方案。看到和研究解决同一问题的不同方法是非常有益的。