Fue*_*led 5 c# windows generic-list device-driver c#-2.0
首先,我很可能是以错误的方式处理我的问题,在这种情况下,我很乐意接受替代方案.
我想要实现的是检测USB设备连接到计算机后创建的驱动器.
这是简化的工作流程:
// Get list of removable drives before user connects the USB cable
List<string> listRemovableDrivesBefore = GetRemovableDriveList();
// Tell user to connect USB cable
...
// Start listening for a connection of a USB device
...
// Loop until device is connected or time runs out
do
{
...
} while
// Get list of removable drives after USB device is connected
List<string> listRemovableDrivesAfter = GetRemovableDriveList();
// Find out which drive was created after USB has been connected
???
Run Code Online (Sandbox Code Playgroud)
GetRemovableDriveList
返回可移动驱动器号的字符串列表.我的想法是在连接设备之前获取可移动驱动器列表,并在连接设备后获取另一个列表,并且通过从第二个列表中删除第一个列表的内容,我将留下刚刚连接的驱动器(通常只有一个).
但我找不到一种简单的方法从另一个"减去"一个列表.任何人都可以建议一个解决方案,甚至是一个更好的方法来实现我想要做的事情.
注意:项目的目标是.NET framework 2.0,因此无法使用LINQ.
谢谢!
对于少量元素,则foreach
带有Contains
调用的循环应该可以解决问题:
List<string> listRemovableDrivesBefore = GetRemovableDriveList();
// ...
List<string> listRemovableDrivesAfter = GetRemovableDriveList();
List<string> addedDrives = new List<string>();
foreach (string s in listRemovableDrivesAfter)
{
if (!listRemovableDrivesBefore.Contains(s))
addedDrives.Add(s);
}
Run Code Online (Sandbox Code Playgroud)
如果集合有很多元素,那么您可以使用 aDictionary<K,V>
而不是 来提高查找效率List<T>
。(理想情况下,您应该使用 a HashSet<T>
,但这在框架的版本 2 中不可用。)