获取列表中给定项目的上一个/下一个项目. [英] Get previous/next item of a given item in a List<>

查看:66
本文介绍了获取列表中给定项目的上一个/下一个项目.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这个列表:1、3、5、7、9、13

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

例如,给定值是:9,上一项是7,下一项是13

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

如何使用C#实现呢?

How can I achieve this using C#?

推荐答案

您可以使用 indexer 来获取所需索引处的元素.向索引添加一个将获得 next ,从索引中减去一个将为您 previous 元素.

You can use indexer to get element at desired index. Adding one to index will get you next and subtracting one from index will give you previous element.

int index = 4; 
int prev = list[index-1];
int next = list[index+1];

您将必须检查下一个和上一个索引是否存在,否则,您将得到

You will have to check if next and previous index exists other wise you will get IndexOutOfRangeException exception. As List is zero based index so first element will have index 0 and second will have 1 and so on.

if(index - 1 > -1)
   prev = list[index-1];
if(index + 1 < list.Length)
   next = list[index+1];

这篇关于获取列表中给定项目的上一个/下一个项目.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆