Reputation:
I have a list of:
class test
{
name,
timestamp
}
and I'd like to get all the last (newest) tests that have the same name. Many tests have same timestamp.
Eg:
name1, 2012-10-25 3:00PM
name1, 2012-10-25 3:00PM
name2, 2012-10-25 3:05PM
name2, 2012-10-25 3:05PM
name1, 2012-10-25 3:10PM
name1, 2012-10-25 3:10PM
name2, 2012-10-25 3:15PM
name2, 2012-10-25 3:15PM
I only need to get the last tests for each name:
name1, 2012-10-25 3:10PM
name1, 2012-10-25 3:10PM
name2, 2012-10-25 3:15PM
name2, 2012-10-25 3:15PM
Upvotes: 1
Views: 1594
Reputation: 3425
Try this:
var q = from l in list
group l by l.Name into g
select new
{
Name = g.Key,
Max = g.Max (x => x.Timestamp)
} into x
from y in list
where x.Name == y.Name && x.Max == y.Timestamp
select y;
What happens here is first a grouping on list
by Name
, and doing that I select for each group the max Timestamp
. This goes into x
. Then I rejoin the same list
to the grouped one, matching all the pairs from the grouping, this way I'm selecting all the original items matching the grouped items.
Upvotes: 0
Reputation: 116138
var groups = list.GroupBy(x => x.name)
.Select(x => new test{
Name = x.Key,
TimeStamp = x.Max(y => y.timestamp)
})
.ToList();
Upvotes: 1