0

I have a Model called JobReport which looks like this (simplified)

public class JobReport
{
    public JobReport()   
    {
        WorkOrders = new List<WorkOrder>();
    }
    public int JobID { get; set; }
    public List<WorkOrder> WorkOrders{ get; set; }
}

public class WorkOrder
{
    public WorkOrder()   
    {
        Total = 0;
    }
    public string Trade { get; set; }
    public int WorkOrderID { get; set; }
    public decimal? Total { get; set; }
}

I'd like to run a Linq query which gets me all the Jobs that have WorkOrders that have a trade which is in a passed array.

var trades = new string[] { }

I've tried something like the following which doesn't work, as it tries to get me a list of workorders, when I actually need the underlying jobs.

The problem appears to be because I'm calling Select

var jobsDB = db.Jobs.Include(x=>x.WorkOrders).ToList();

var jobs = (from p in jobsDB
                    select new JobReport()
     {
        JobID = p.JobID,
        WorkOrders = p.WorkOrders.ToList()
     }


jobs = jobs
    .Select(x => x.WorkOrders
    .Where(y => trades.Contains(y.Trade)));

1 Answer 1

3

This will work:

jobs = jobs
    .Where(x => x.WorkOrders.Any(y => trades.Contains(y.Trade)));

The way I usually tackle these problems is that I look at what the outcome must be (a list of jobs) - that means we need to put the Where first, and we must look for a condition for a job to be included. It's a bit like constructing a SQL query - in fact you can use the SQL like query syntax for most LINQ tasks, if you prefer.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.