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

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

    int index = list.IndexOf(9); // find the index of the given number
    
    // find the index of next and the previous number
    // by taking into account that 
    // the given number might be the first or the last number in the list
    int prev = index > 0 ? index - 1 : -1;
    
    int next = index < list.Count - 1 ? index + 1 : -1;
    
    int nextItem, prevItem;
    
    // if indexes are valid then get the items using indexer 
    // otherwise set them to a temporary value, 
    // you can also use Nullable instead
    nextItem = prev != -1 ? list[prev] : 0;
    prevItem = next != -1 ? list[next] : 0;
    

提交回复
热议问题