Reputation: 11304
I have data from external system in a tuple like this, have lots of item2 and item 3 combinations with different datetime.
var data = new List<Tuple<DateTime, string, string>>
{
new Tuple<DateTime, string, string>(new DateTime(2021, 04, 01, 5, 10, 20), "A1", "X1"),
new Tuple<DateTime, string, string>(new DateTime(2021, 04, 01, 6, 10, 22), "A1", "X1"),
new Tuple<DateTime, string, string>(new DateTime(2021, 04, 02, 7, 11, 21), "A2", "X2")
};
Now I need to fetch MAX datetime against each unique item2 & item3 combinations and return result should be this,
var result = new List<Tuple<DateTime, string, string>>
{
new Tuple<DateTime, string, string>(new DateTime(2021, 04, 01, 6, 10, 22), "A1", "X1"),
new Tuple<DateTime, string, string>(new DateTime(2021, 04, 02, 7, 11, 21), "A2", "X2")
};
I am able to fetch MAX datetime for each item2 and item3 combinations where I am passing these values as hard code,
var maxTimestamp = data.Where(t => t.Item2 == "A1" && t.Item3 == "X1").Max(t => t.Item1);
but I need to iterate each item2 and item3 combinations, how to do this?
Upvotes: 0
Views: 33
Reputation: 8743
Use GroupBy
:
var maxTimestamps = data.GroupBy(x => new { x.Item2, x.Item3}).
Select(x => x.OrderByDescending(y => y.Item1).First());
You will get groups with the same Item2
and Item3
. Sort these groups by their date and pick the first date of each group.
Upvotes: 1