我设计了一个查询并添加了分组,但分组并没有将记录减少到最年轻的ContractEndDate。它似乎对结果没有影响。
public IQueryable<SoonObsoleteContractsViewModel> Get()
{
var countries = UnitOfWork.GetAll<Country>();
var companies = UnitOfWork.GetAll<Company>();
var contracts = UnitOfWork.GetAll<Contract>();
var query = from country in countries
join company in companies on country.Id equals company.CountryId
join contract in contracts on company.Id equals contract.CompanyId
select new SoonObsoleteContractsViewModel
{
CountryName = contry.Name,
CompanyName = company.Name,
CompanyId = company.CompanyId
ContractBeginDate = contract.Begin,
ContractEndDate = contract.End,
ContractId = contract.Id
};
query.GroupBy(c => c.CompanyId, (key, e) => e.OrderBy(f => f.ContractEndDate).First());
return query;
}
任何帮助都将不胜感激。
答案 0 :(得分:1)
按国家/地区和公司分组,然后获取具有最近合同结束日期的组中的记录。
var result = query
.GroupBy(_ => new { _.CountryName, _.CompanyId})
.Select(g => g.OrderByDescending(c => c.ContractEndDate).First())
.ToList();
或换句话说
var query = from contry in countries
join company in companies on country.Id equals company.CountryId
join contract in contracts on company.Id equals contract.CompanyId
let viewModel = new SoonObsoleteContractsViewModel
{
CountryName = contry.Name,
CompanyName = company.Name,
CompanyId = company.CompanyId
ContractBeginDate = contract.Begin,
ContractEndDate = contract.End,
ContractId = contract.Id
}
group viewModel by new { viewModel.CountryName, viewModel.CompanyId } into g
select g.OrderByDescending(c => c.ContractEndDate).First();
答案 1 :(得分:0)
感谢NKosi,我终于解决了它:
var query = from contry in countries
join company in companies on country.Id equals company.CountryId
join contract in contracts on company.Id equals contract.CompanyId
let viewModel = new SoonObsoleteContractsViewModel
{
CountryName = contry.Name,
CompanyName = company.Name,
CompanyId = company.CompanyId
ContractBeginDate = contract.Begin,
ContractEndDate = contract.End,
ContractId = contract.Id
}
group viewModel by new { viewModel.CountryName, viewModel.CompanyId } into g
select g.OrderByDescending(c => c.ContractEndDate).FirstOrDefault();
我所要做的只是将 First()更改为 FirstOrDefault !否则,查询将生成一个空列表。