我想只获得最大的StartDate,它的日期倍数与相同的CustomNumber
有什么建议吗?
我的简化代码
from Cus in Customers
where Cus.CustomNumber == 2
group Cus by new
{ Cus.Name,Cus.City,Cus.StartDate}
into grp
select new
{
Name = grp.Key.Name,
City = grp.Key.City,
StartDate = grp.Key.StartDate,
//I have tried, but it doesnt work for me
//StartDate = grp.Max(Cus=> grp.Key.StartDate)
}
答案 0 :(得分:1)
你可以尝试这个:
var result = from Cus in Customers
where Cus.CustomNumber == 2
group Cus by new
{ Cus.Name, Cus.StartDate}
into grp
select new
{
Name = grp.Key.Name,
StartDate = grp.Max(x=>x.StartDate)
};
使用grp
您可以访问您在linq查询中创建的随机组,然后使用名为Max
的扩展方法获得组中的最大StartDate
。
<强>更新强>
由于您现在在分组之前有联接,您必须将代码更改为以下代码:
var result = from res in
(from customer in Customers
join house in Houses
on customer.CustomNumber equals house.CustomNumber
where customer.CustomNumber == 2
select new { Name = customer.Name, StartDate = house.StartDate })
group res by res.Name into grp
select new { Name = grp.Key, StartDate = grp.Max(x=>x.StartDate) };
更新#2
如果您希望在结果中同时获得客户的姓名和城市,则必须使用以下代码:
var result = from res in
(from customer in Customers
join house in Houses
on customer.CustomNumber equals house.CustomNumber
where customer.CustomNumber == 2
select new { Name = customer.Name, City = customer.Name, StartDate = house.StartDate })
group res by new { res.Name, res.City } into grp
select new
{
Name = grp.Key.Name,
City = grp.Key.City,
StartDate = grp.Max(x=>x.StartDate)
};
答案 1 :(得分:1)
尝试以下代码
StartDate = grp.Max(x => x.StartDate)