【问题标题】:How to check if there is an element at the specific index in a list?如何检查列表中特定索引处是否有元素?
【发布时间】:2014-08-20 11:40:46
【问题描述】:

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

Product[i]

有没有?这张支票怎么写?

【问题讨论】:

    标签: c# list


    【解决方案1】:

    如果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
    }
    

    【讨论】:

      【解决方案2】:

      这样试试

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

      如果您想检查该特定数组中是否存在索引,则只需检查该数组的长度即可。

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

      【讨论】:

      • 该代码检查列表中项目的实际内容,而不是索引。此外,它对于这个问题也不是很有效。
      【解决方案3】:
      return (Product.Count() -1) <= i;
      

      或者如果你觉得自己很老套:

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

      Product.Skip(i).Any()
      

      或者...

      【讨论】:

        猜你喜欢
        • 2015-03-14
        • 1970-01-01
        • 2022-07-06
        • 2014-05-13
        • 2012-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多