如何检查列表中特定索引是否有元素?

时间:2014-08-20 11:40:47

标签: c# list

如何检查列表中特定索引是否有元素,例如

Product[i]

是否存在?怎么写这个支票?

3 个答案:

答案 0 :(得分:2)

如果i是您想要的索引,请查看Count

if (i >= 0 && (list.Count - 1) >= i)
{
    // okay, the item is there
}

如果谈论可空类型,您还可以检查该索引上的项目是否不是null

if (i >= 0 && (list.Count - 1) >= i && list[i] != null)
{
    // okay, the item is there, and it has a value
}

答案 1 :(得分:0)

试试这个

if (Product.Contains(yourItem))
   int Index = Array.IndexOf(Product, yourItem);

如果要检查索引是否存在于该特定数组中,那么您只需检查该数组的长度。

if (i < Product.Length && i > -1)
    //yes it has

答案 2 :(得分:0)

return Product.Count() <= i;

或者如果你感觉自己是hackish:

try { var x = Product[i]; return true; } catch(ArrayIndexOutOfBoundException) { return false; }

Product.Skip(i).Any()

...或

相关问题