简体   繁体   中英

Finding last item of a set of items within a collection?

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.

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());

You can try this code:

collection
.GroupBy(x => x.Key)
.Select(x => new { Key = x.Key, MaxSeq = x.Max(e => e.Seq));

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 };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM