【问题标题】:Get position of each item in a list获取列表中每个项目的位置
【发布时间】:2015-01-28 17:31:16
【问题描述】:

如果我正在遍历列表中的项目,我如何获取每个项目的位置(即,如果有 5 个项目,则为 1、2、3、4 和 5?

    public void AllocatePosition(List<DbConnect.BidList> createBidList)
    {
        for (int i = 0; i < createBidList.Count; i++)
        {
            MessageBox.Show(createBidList[i].ToString()); // show position of item (i.e. is it first, second, third...on the list
        }
    }

【问题讨论】:

  • 也许我错过了重点:i.ToString() ?
  • 您可以使用createBidList.IndexOf(createBidList[i]),但是当您已经拥有 i 时,这似乎有点过头了。
  • 对不起小伙子们 - 有一个金发的时刻
  • 这发生在我们所有人@methuselah。
  • @dsolimano 对我来说,更多的是,不可能你问如何获得i,那么你实际上问的是什么?

标签: c# list


【解决方案1】:
public void AllocatePosition(List<DbConnect.BidList> createBidList)
{
    for (int i = 0; i < createBidList.Count; i++)
    {
        MessageBox.Show("Position: " + i + " Item: " + createBidList[i].ToString());
    }
}

i 变量包含位置。 i 通常用于 for 循环,传统上它代表“索引”。

【讨论】:

    【解决方案2】:

    看看

    for (int i = 0; i < createBidList.Count; i++)
    

    i 是项目在列表中的位置,除非我遗漏了什么。所以你想要

    for (int i = 0; i < createBidList.Count; i++)
    {
        MessageBox.Show(i.ToString()); // show position of item (i.e. is it first, second, third...on the list
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-27
      • 1970-01-01
      • 2015-10-26
      • 2010-09-26
      • 2019-02-02
      • 1970-01-01
      • 1970-01-01
      • 2018-09-21
      相关资源
      最近更新 更多