一直在玩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();
这样可以正常工作,但它会返回所有合同,甚至是一些不在“1月”的合同。我错过了一步吗?
答案 0 :(得分:3)
您的查询中没有任何内容可以过滤合同(Company.Contract
) - 只有公司本身。您可能需要单独执行此操作,可能通过Where
上的.Contract
。
如果要从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};
答案 1 :(得分: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();