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

后端 未结 11 1275
余生分开走
余生分开走 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:12

    Following may be helpful

     int NextValue = 0;
     int PreviousValue =0;
     int index = lstOfNo.FindIndex(nd =>nd.Id == 9);
    
     var Next = lstOfNo.ElementAtOrDefault(index + 1);
     var Previous = lstOfNo.ElementAtOrDefault(index - 1);
    
     if (Next != null)
         NextValue = Next;
    
    
    if (Previous != null)
       PreviousValue = Previous;
    

提交回复
热议问题