Reputation: 73
I want to only get out the max StartDate, its multiples of dates with the same CustomNumber
Any suggestions?
My simplified code
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)
}
Upvotes: 1
Views: 93
Reputation: 53958
You could try this one:
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)
};
Using grp
you have access to the random group you create in your linq query, then using the extension method called Max
you get the maximum StartDate
in your group.
UPDATE
Since now you have a join before the grouping, you have to change your code to the following one:
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) };
UPDATE #2
If you want you get both the customer's Name and City in your result, you have to use the following code:
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)
};
Upvotes: 1