tags:

views:

73

answers:

2

Have been playing around with linq but there is one thing I cant seem to make it do.. here is the situation.. lets say you have..

public class Job
{
    public DateTime? CreatedDate { get; set; }
}

public class Company
{
    public string Name { get; set; }
    public List<Job> Contract { get; set; }
}

Now what I want to do is populate a List of Companies then only get companies with Contracts created in.. lets say January.. something like this..

String[] MonthName = { "January", "February", "March", "April", "May", "June", "July", "Agust", "September", "October", "November", "December" };

List<Company> Companies = PopulateData();
List<Company> ValidCompany = Companies.Where(CompanyFilter => CompanyFilter.Contract.Any(ContractFilter => MonthName[ContractFilter.CreatedDate.Value.Month - 1] == "January")).ToList();

This works fine, but it returns all Contracts even some which are not in "January". Am I missing a step?

+1  A: 

Original post:

List<Company> ValidCompany = (
   from c in Companies
   let janContracts = c.Contracts
      .Where(con => MonthName[con.CreatedDate.Value.Month - 1] == "January")
   where janContracts.Any()
   select new Company
   {
       Name = c.Name,
       Contracts = janContracts.ToList()
   }).ToList();


Update: with extension methods

var janCompanies = Companies.Select(c=>
    new Company
    {
       Name = c.Name,
       Contracts = c.Contracts
           .Where(con => MonthName[con.CreatedDate.Value.Month - 1] == "January")
           .ToList()
    });
List<Company> ValidCompany = janCompanies
    .Where(c=>c.Contracts.Any())
    .ToList();
eglasius
I cant believe it was that simple.. I just forgot to assign the new results..
Fredrick
+2  A: 

There is nothing in your query that would filter the contracts (Company.Contract) - only the companies themselves. You would need to do that separately, perhaps via a Where on .Contract.

If you are loading the data from LINQ-to-SQL, then AssociateWith may be uesful.

If you want all contracts in the range regardless of company, then perhaps SelectMany:

var qry = from company in Companies
          from contract in company.Companies
          where contract.CreatedDate.Value.Month == ... etc
          select new {Company = company, Contract = contract};
Marc Gravell