Find next record in a set: LINQ

后端 未结 3 1630
遇见更好的自我
遇见更好的自我 2020-12-29 09:27

I have a list of objects which all have an id property

E.g

1, 10, 25, 30, 4

I have a currentId and I need to find the next Id in the list

So

相关标签:
3条回答
  • 2020-12-29 09:35

    There are quite a few solution. I suggest something like the following.

    var next = items
        .Where(item => item.Id > currentId)
        .OrderBy(item => item.Id)
        .First();
    
    var next = items
        .OrderBy(item => item.Id)
        .First(item => item.Id > currentId);
    

    If you want the ids in the order they appear in the collection, you could use the following.

    var next = items
        .SkipWhile(item => item.Id != currentId)
        .Skip(1)
        .FirstOrDefault();
    

    If this returns null, you have tried to get next item of the last item.

    0 讨论(0)
  • 2020-12-29 09:36

    Without re-ordering (note I edit slightly as I think I misread the question):

    int[] data = {1, 10, 25, 30, 4};
    int last = 25;
    var next = data.SkipWhile(i => i != last).Skip(1).First();
    

    Obviously, if data was a set of objects, something like:

    var next = data.SkipWhile(obj => obj.Id != last).Skip(1).First();
    
    0 讨论(0)
  • 2020-12-29 09:57
    int currentId = 25;
    var next = yourCollection.Where(i => i.Id > currentId).OrderBy(i => i.Id).First();
    
    0 讨论(0)
提交回复
热议问题