Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Using ArrayList.IndexOf with multiple identical items

Tags:

c#

arraylist

I've got a situation where I'm using an ArrayList to store a list of file names (full file path). When I add multiple items of the same file to the array, then use ArrayList.IndexOf to find the index (I'm reporting progress to a BackgroundWorker), it always returns the index of the first item since it's searching by the file name. This causes a problem with a progress bar, i.e. I'm processing 3 files, and when complete, the bar is only 1/3 full.

Here's some sample code (I'm simply adding items here, but in the real code they are added from a ListBox):

ArrayList list = new ArrayList();

list.Add("C:\Test\TestFile1.txt");
list.Add("C:\Test\TestFile1.txt");
list.Add("C:\Test\TestFile1.txt");

var files = list;
foreach (string file in files)
    backgroundWorker1.ReportProgress(files.IndexOf(file) + 1);

When this runs, only 1 "percent" of progress is reported, since the IndexOf is finding the same file every time. Is there any way around this? Or does anyone have a suggestion on another way to get the index (or any unique identifier for each item)?

like image 735
Adam Elders Avatar asked Feb 07 '23 14:02

Adam Elders


1 Answers

The simplest approach is just to use the index to iterate:

for (int i = 0; i < list.Count; i++)
{
    backgroundWorks.ReportProgress(i + 1);
    // Do stuff with list[i]
}
like image 176
Jon Skeet Avatar answered Feb 12 '23 10:02

Jon Skeet