Reputation: 6091
I've got a collection of items all with a Key and a "sequence" number. I am trying to find the items with the "last" sequence number for each of the keys...but the sequence numbers are within a "window" (as they are date based).
Example Data
Key Seq other data.....
___ ___ _________________
ABC 4
ABC 5
ABC 6
FGH 1
FGH 2
FGH 3
FGH 4
FGH 5
FGH 6
FGH 7
FGH 8
FGH 9
FGH 10
OPQ 6
RST 3
RST 4
and I would be looking for the result:
ACB 6
FGH 10
OPQ 6
RST 4
I can get this by looping through each key one-by-one, but seems there must be a cleaner way.
Upvotes: 0
Views: 58
Reputation: 104
You can also do it by Linq: This code if you want to select last
var result = from data in YourObject
group data by data.Key into item
select new { Key = item.Key, Seq = item.Last().Seq, OtherDataOjbect= item.Last().OtherDataOjbect };
And if you want to select max, Use this:
var result = from data in YourObject
group data by data.Key into item
select new { Key = item.Key, Seq = item.Max(x => x.Seq), obj = item.Single(x => x.Seq == item.Max(z => z.Seq)).obj };
Upvotes: 0
Reputation: 81
You can try this code:
collection
.GroupBy(x => x.Key)
.Select(x => new { Key = x.Key, MaxSeq = x.Max(e => e.Seq));
Upvotes: 0
Reputation: 70652
Are the items guaranteed to be sorted in the original data?
If so, then you can do this:
var result = items.GroupBy(item => item.Key).Select(group => group.Last());
If they can initially be out of order, then this would work:
var result = items.GroupBy(item => item.Key)
.Select(group => group.OrderByDescending(item => item.Seq).First());
Upvotes: 2