2009-04-16 96 views
1

必要的數據已經被玩弄LINQ,但有一件事我似乎無法讓它做..這裏的情況..可以說你有..過濾與LINQ

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

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

現在我想要做的就是填充公司的名單則只能獲得公司在創建合同..讓說一月..這樣的事情..

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(); 

這工作得很好,但它甚至返回所有合同有些不在一月」。我錯過了一步嗎?

回答

2

原帖:

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(); 

更新:與擴展方法

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(); 
+0

我不能相信這是這麼簡單..我只是忘了分配新的結果.. – Fredrick 2009-04-16 07:56:18

3

有沒有在你的查詢,將過濾合同(Company.Contract) - 只有企業自己。您需要單獨執行此操作,可能需要.Contract上的Where

如果您正在從LINQ-to-SQL加載數據,則AssociateWith可能會很好用。

如果你想在範圍內的所有合同,無論公司的,那麼也許SelectMany

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