一直在和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();
这可以正常工作,但它会返回所有合同,即使某些合同不在“一月”中。我错过了一步吗?
最佳答案
原始帖子:
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();