C# : Removing an item from a List without knowing its index?
I'm suing FileSystemWatcher class to monitor a folder and update the list
as events arise. I'm using the following class to hold information for
each file:
public class FileItem
{
public string Name { get; set; }
public string Path { get; set; }
}
The following list holds the collection of that information:
public static List<FileItem> folder = new List<FileItem>();
I added some FileItem objects into the list. However, to remove a specific
item that has a matching name, I couldn't just use foreach() loop because
enumerations change and as soon as the file is removed, I get an
exception. So, I added a break (since there will only be one file with the
same name) to break out of the foreach() loop after an item was removed...
but I'm not sure if it's the most efficient way to do it. Is there a
simpler and more appropriate way? Here's my code for the removal:
private static void OnChanged(object source, FileSystemArgs e)
{
if (e.ChangeType == WatcherChangeTypes.Deleted)
{
foreach (var item in folder)
{
if (item.Name == e.Name)
{
folder.Remove(item);
folder.TrimExcess();
break;
}
}
}
}
No comments:
Post a Comment