【发布时间】:2014-08-20 11:40:46
【问题描述】:
如何检查列表中特定索引处是否有元素,比如
Product[i]
有没有?这张支票怎么写?
【问题讨论】:
如何检查列表中特定索引处是否有元素,比如
Product[i]
有没有?这张支票怎么写?
【问题讨论】:
如果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
}
【讨论】:
这样试试
if (Product.Contains(yourItem))
int Index = Array.IndexOf(Product, yourItem);
如果您想检查该特定数组中是否存在索引,则只需检查该数组的长度即可。
if (i < Product.Length && i > -1)
//yes it has
【讨论】:
return (Product.Count() -1) <= i;
或者如果你觉得自己很老套:
try { var x = Product[i]; return true; } catch(ArrayIndexOutOfBoundException) { return false; }
或
Product.Skip(i).Any()
或者...
【讨论】: