使用For循环比较和删除列表项

时间:2017-08-18 07:27:45

标签: c#

我有一个下载列表和一个排除列表。

我想只使用for循环保留File2.zip

然而,循环无法正常工作,同时保留File2.zipFile4.zip

http://rextester.com/UWCT32568

这是我想要应用于更大项目的示例代码。

在这种情况下,我不想使用download = download.Except(excluded).ToList();

http://rextester.com/HBQZPC42707

List<string> download = new List<string>();
download.Add("File1.zip");
download.Add("File2.zip");
download.Add("File3.zip");
download.Add("File4.zip");
download.Add("File5.zip");

List<string> excluded = new List<string>();
excluded.Add("File1.zip");
// keep File2.zip
excluded.Add("File3.zip");
excluded.Add("File4.zip");
excluded.Add("File5.zip");


// Remove Excluded Files from Download List
//
int count = download.Count();

for (int i = 0; i < count; i++)
{
    // index out of range check
    if (download.Count() > i )
    {
        // Remove
        if (excluded.Contains(download[i]))
        {
            download.RemoveAt(i);
            download.TrimExcess();
        }
    }
}


// Display New Download List
//
download.ForEach(x=>Console.WriteLine(x));

2 个答案:

答案 0 :(得分:2)

删除项目时,您希望向后循环:

//for (int i = 0; i < count; i++)
for (int i=count-1; i>=0; i--)
{
    // index out of range check
    //if (download.Count() > i ) - No longer needed.
    //{
        // Remove
        if (excluded.Contains(download[i]))
        {
            download.RemoveAt(i);
            download.TrimExcess();
        }
    //}
}

更改后,显示“File2.zip”。

答案 1 :(得分:2)

  1. 删除时,向后循环
  2. 使用HashSet<string>更有效地查找
  3. 上的项目

    实现:

     // Items to remove: excluded.Contains(item) is more efficient if excluded is a HashSet<T>
     HashSet<string> excluded = new HashSet<string>() {
       "File1.zip",
       "File3.zip",
       "File4.zip",
       "File5.zip",  
     };
    
     for (int i = download.Count - 1; i >= 0; --i)
       if (excluded.Contains(download[i])) // Shall we remove i-th item?
         download.RemoveAt(i);             // If yes, remove it 
    
     // If you want to trim the list, do not do it within the loop, 
     // but remove all the required items and only then trim (once!) the list
     download.TrimExcess(); // Not necessary, but possible
    

    编辑:在(罕见的)情况下必须循环前进(例如,如果必须按照创建顺序删除项目)循环

     for (int i = 0; i < download.Count;)   // please, notice, no increment here
       if (excluded.Contains(download[i]))  // Shall we remove i-th item?
         download.RemoveAt(i)               // If yes, remove it
       else
         i += 1;                            // If no, inspect the next item