如何解决有没有办法可以缓存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; }
// ...
}
现在给定雇员列表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语句完成整个操作的方法,我将不胜感激。
谢谢。
解决方法
您可以尝试这样的事情:
f2 <- function(df,...){
params <- list(...)
res <- map_df(colnames(df),~ do.call(
f1,c(list(x = df[,.],a=.),params)))
return(res)
}
在这里,您从员工中选择想要的项目,然后得到第一个不为空的项目
, SelectMany
也可以在这里工作。
static public Project GetProject(List<Employee> employees,Guid id)
=> employees
.SelectMany( e => e.GetProjects()?.EmployeeProjects)
.FirstOrDefault( p => p.ProjectId == id);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。