[英]Get the next object in list after the object with current ID
I know the title is confusing so I will try my best to explain here... 我知道标题令人困惑,所以我会尽力在这里解释...
I have 我有
class T{
int id;
string value;
}
List<T> objs;
in my code when I retrieve the initial list I grab the first id with 在我的代码中,当我检索初始列表时,我使用了第一个ID
int currentID = objs.FirstOrDefault().id;
now I need to grab next. 现在我要抓住下一个。 not knowing the current position of where I am how can I grab the next item id... 不知道我现在的位置如何获取下一个商品ID ...
objs.select(x => x.id)
.where(//you are the object that exists after the one with currentID);
如果要在某个元素之后获取下一个元素,则可以使用SkipWhile()
和Skip()
方法:
objs.SkipWhile(x => x.id == currentID).Skip(1).FirstOrDefault();
You are just indexing, so use ElementAt
: 您只是在建立索引,因此请使用ElementAt
:
int i = 0; //current position
int currentID = objs.ElementAt(i).id;
i++;
Execute in a loop to get the next one, etc. 循环执行以获取下一个,依此类推。
If you actually just want to iterate through all elements, just use a foreach
: 如果您实际上只想遍历所有元素,请使用foreach
:
foreach (T obj in objs)
{
int currentID = obj.id;
}
Finally, you could use GetEnumerator
and utilize the MoveNext
function along with the Current
property. 最后,您可以使用GetEnumerator
并利用MoveNext
函数和Current
属性。 This is basically using a foreach
but controlling the iteration yourself. 基本上,这是使用foreach
但可以自己控制迭代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.