How to subtract one general list from another in C # 2.0

First of all, it is very good that I approach my problem incorrectly, and in this case I gladly accept the alternatives.

I am trying to determine which drive was created after connecting the USB device to the computer.

Here is a simplified workflow:

// 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
???

GetRemovableDriveListreturns a list of strings of removable drives. My idea was to get a list of removable drives before the device is connected, and another list after it is connected, and that by deleting the contents of the first list from the second, I would leave the drives that were just connected (usually only one).

But I cannot find an easy way to “subtract” one list from another. Anyone can offer a solution or even a better way to achieve what I'm trying to do.

: .NET framework 2.0, LINQ .

!

+5
3

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);
}

, , Dictionary<K,V>, List<T>. ( HashSet<T>, 2 .)

+1

- :

public static IEnumerable<T> Subtract<T>(IEnumerable<T> source, IEnumerable<T> other)
{
    return Subtract(source, other, EqualityComparer<T>.Default);
}

public static IEnumerable<T> Subtract<T>(IEnumerable<T> source, IEnumerable<T> other, IEqualityComparer<T> comp)
{
    Dictionary<T, object> dict = new Dictionary<T, object>(comp);
    foreach(T item in source)
    {
        dict[item] = null;
    }

    foreach(T item in other)
    {
        dict.Remove(item);
    }

    return dict.Keys;
}
+3

Linq Subtract Insersect, .

A = .

B = .

A - (A Intersect B) = B - ( B) =

var intersect = A.Intersect(B);

var removed = A.Substract (intersects); var new = B.Substract (intersects)

Hope this works for you.

+1
source

All Articles