【问题标题】:Using list.Count() to set limiting number of for loop error [duplicate]使用 list.Count() 设置 for 循环错误的限制数量 [重复]
【发布时间】:2021-08-05 18:30:42
【问题描述】:

我正在使用基于列表中项目数声明 INT 的 for 循环。我正在填充的列表是动态的,基于目录中的文件列表。逻辑应该是,如果计数等于或超过 1k 条记录,则一次加载 1k 条记录,否则,如果计数较少,则计算列表中的项目并将其设置为 for 循环的最大值。然而 for 循环只运行 499 次并且出现错误(图片)。 THIS ERROR IMAGE.

有人知道如何解决发生的错误吗?

下面是代码的核心,便于理解。

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;
using System.Linq;

namespace ViewProductImages
{
    public partial class Form1 : Form
    {
        

        public Form1()
        {
            InitializeComponent();
        }
             
                //new list
        List<string> filenames = new List<string>();          
       
        private void txtDirectory_TextChanged(object sender, EventArgs e)
        {
            
                //clear list - added peace of mind
            filenames.Clear();   

           
               //list is populated here via Directory.Getfiles


                //Sorted here kinda
                filenames.Sort();



        }
                 //Declare INT for for loop

        int maxImagesToShow;

        private void button1_Click(object sender, EventArgs e)
        {

                //Setting value for INT - IF over 1k records, set to 1k, IF under - set to actual list item count

            if (filenames.Count() >= 1000)
            {
                maxImagesToShow = 1000;
            }
            else
            {
                maxImagesToShow = filenames.Count();
            }

            try
            {

                //for loop - loops based on value in INT

                for (int i = 0; i < maxImagesToShow; i++)
                {                  
                    var filename = filenames[i];   

                   

                //remove current item being processed from the list(filenames)

                    filenames.Remove(filename);


                }

            }
            catch (Exception ex)
            {
                
            }
        }
    }
}

【问题讨论】:

  • 提示:假设列表中有 5 个项目,那么您将从 0 到 4 进行迭代。然后你调用Remove 两次......列表中有多少项目?删除前两个元素后,元素 4 是什么? (为什么要在循环中完全删除项目?我建议使用 List.RemoveRange...)
  • 请记住在您的问题中包含错误消息及其堆栈跟踪作为文本。即使在屏幕截图中的对话框中,您也应该能够按 CTRL+C 并复制它。

标签: c# list for-loop


【解决方案1】:

您正在通过从中删除项目来减小列表的大小,但for 循环保持原始条件并期望看到多达 1000 个项目。如果删除它们,则循环结束时列表中不会有 1000 个项目。您还将跳过项目,因为当您从列表的开头删除时,您会减少所有其他项目的索引。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 2020-04-05
    • 1970-01-01
    • 2016-04-24
    相关资源
    最近更新 更多