How to write C # lamba queries more efficiently

Is there a way to shorten these three lambda expressions? Now I need three steps to get the result.

First, I look for all the goals that belong to someone. Then I look at the link table for all the project objects that belong to these goals. The final lambda returns all projects by their identifier.

I cannot help but think that there is a more efficient way, but I cannot find it ...

public async Task<List<Project>> GetProjectsFromSomeone(string someone) {
    var targetIds = from target in Context.Targets
                     where target.Someone.ToLower().Contains(someone.ToLower())
                     select target.Id;

    var projectIds = from pt in Context.ProjectTargets
                 where targetIds.Any(id  => id == pt.TargetId)
                 select pt.ProjectId;

    var projects = from prj in Context.Projects
                where projectIds.Any(id => id == prj.Id)
                select prj;

    return await projects.ToListAsync(); 
}

public class ProjectTarget
{
    public int ProjectId { get; set; }
    public int TargetId { get; set; }

    public Project Project { get; set; }
    public Target Target { get; set; }
}

public class Target
{
    public int Id { get; set; }
    public string Code { get; set; }
    public string Someone { get; set; }
}

public class Project
{
    public int Id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
}
+4
source share
2 answers

You can use Linq joins. Linq will take care of the connections and conditions.

public async Task<List<Project>> GetProjectsFromSomeone(string someone) 
{    
    var projects = from target in Context.Targets
                join pt in Context.ProjectTargets on target.Id equals pt.TargetId
                join prj in Context.Projects on pt.ProjectId equals prj.Id
                where target.Someone.ToLower().Contains(someone.ToLower())
                select prj;
    return await projects.ToListAsync(); 
}

Hope this helps!

+6
source

I think you can use join requests.

from P in Context.Projects
join PT in Context.ProjectTargets on P.Id equals PT.id
join T in Context.Targets on PT.TargetId equals T.id
  .Select(m => new
  {
      //select the fields which you want select
  });
+1
source

Source: https://habr.com/ru/post/1692971/


All Articles