如何检查列表中是否存在值(在超出范围之前)

本文关键字:范围 是否 何检查 检查 列表 存在 | 更新日期: 2023-09-27 18:20:54

我有这个列表:

IList<Modulo> moduli = (from Modulo module in Moduli
                       select module).ToList();

并且我将其循环用于(注意I=I+2):

for(int i=0; i<moduli.Count; i=i+2)
{
}

现在,我必须检查模[I+1]是否存在(所以,下一个元素),否则我会得到一个System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.

我该如何检查?尝试使用:

if(moduli[i+1] != null) 
{
}

但它不起作用!

如何检查列表中是否存在值(在超出范围之前)

以与检查循环条件相同的方式进行检查:

if(i + 1 < moduli.Count) // it exists

请注意<而不是<=,这是原始代码中的一个错误。

怎么样:

if (i + 1 < moduli.Count)
{
  var modulo = moduli[i+1]; // this is safe
}

如果i+1将导致ArgumentOutOfRangeException ,则这不应该是真的

顺便说一句,这不起作用的原因是:

if(moduli[i+1] != null) 

ArgumentOutOfRangeException将在您进行检查后立即抛出。

怎么样

for(int i=0; i <= (moduli.Count - (moduli.Count % 2)); i=i+2)
{
} 

Linq可以为您完成以下工作:)

IList<Modulo> moduli = Moduli.Where((item, index) => ((index % 2) == 0)).
                              ToList();

非常简单:

for(int i=0; i<moduli.Count - 2; i=i+2) { }