【问题标题】:Get Specific number from List [closed]从列表中获取特定数字[关闭]
【发布时间】:2013-08-14 09:19:35
【问题描述】:

我有这个列表 List<string> Url = new List<string>(); 更多元素 >10,我只需要获得 5 个元素。

我尝试在这种模式下得到所有元素:

foreach (string key3 in Url)
            {
                listBox3.Items.Add(key3);
            }

【问题讨论】:

  • 这样就可以将Url中的所有元素添加到listBox3中
  • 您的问题是:......只有第 5 个元素,还是前 5 个元素?
  • 在 stackoverflow 上查看列表中前 N 个元素的答案:stackoverflow.com/questions/319973/…

标签: c# list


【解决方案1】:
IEnumerable<string> firstFiveUrls = Url.Take(5);

Enumerable.Take documentation

所以你可以这样做:

// ObjectCollection.AddRange expects an array 
listBox3.Items.AddRange(Url.Take(5).ToArray()); 

ObjectCollection.AddRange documentation

【讨论】:

  • 另一个列表??不,谢谢=(
  • @Federal09 - 查看更新,您正在添加到需要数组的列表框项目
【解决方案2】:
for (int i = 0; i < 5; i++)
{
    listBox3.Items.Add(Url[i]);
}

如果你能确保总有 > 5 个元素,这应该没问题。

【讨论】:

  • 值得注意的是,使用这种方法,您应该验证输入以确保它在循环之前至少有 5 个元素
【解决方案3】:

试试这个:

for(int i=0; i<5; ++i)
{
  listBox3.Items.Add(Url[i]);
}

【讨论】:

  • 非常感谢,完美!
【解决方案4】:

您可以使用GetRange

Url.GetRange(0,5);

listBox3.Items.AddRange(Url.GetRange(0,5));

【讨论】:

    【解决方案5】:

    带有起始索引和计数..

    List<string> fiveURLs = URL.GetRange(0, 5);
    

    【讨论】:

      【解决方案6】:

      前五个元素

      for (int i = 0; i < Url.Count && i < 5; i++)
          {
               listBox3.Items.Add(Url[i]);
          }
      

      第五个元素

      listBox3.Items.Add(Url[4]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-18
        • 2021-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多