Get previous/next item of a given item in a List<>

后端 未结 11 1417
余生分开走
余生分开走 2021-02-12 03:18

Says I have this List : 1, 3, 5, 7, 9, 13

For example, given value is : 9, the previous item is 7 and the next item is 13

How can I achieve this using C#?

11条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-12 04:19

    var index = list.IndexOf(9);
    if (index == -1) 
    {
       return; // or exception - whater, no element found.
    }
    
    int? nextItem = null; //null means that there is no next element.
    if (index < list.Count - 1) 
    {
       nextItem = list[index + 1];
    }
    
    int? prevItem = null;
    if (index > 0) 
    {
       prevItem = list[index - 1];
    }
    

提交回复
热议问题