VNarasimhaM
VNarasimhaM

Reputation: 1570

how do I get a subset of strings from list 1 which are not present in list2?

I have two lists

list 1 = { "fred", "fox", "jumps", "rabbit"};
list2 ={"fred", "jumps"}

Now I need to get a list3 which contains elements of list1 which are not present in list2. so list 3 should be

list3  = {"fox", "rabbit"};

I can do this manually by using loops but I was wondering if there is something like list3 = list1 - list2 or some other better way than using loops.

Thanks

Upvotes: 2

Views: 374

Answers (2)

Mark Byers
Mark Byers

Reputation: 838376

If you are using .NET 3.5 or newer then you can use Enumerable.Except:

var result = list1.Except(list2);

If you want it as a list:

List<string> list3 = list1.Except(list2).ToList();

For older versions of .NET you could insert the strings from list1 as keys in a dictionary and then remove the strings from list2, then the keys that are left in dictionary is the result.

Dictionary<string, object> d = new Dictionary<string, object>();
foreach (string x in list1)
    d[x] = null;
foreach (string x in list2)
    d.Remove(x);
List<string> list3 = new List<string>(d.Keys);

Upvotes: 10

decyclone
decyclone

Reputation: 30830

list1.Except(list2);

Upvotes: 1

Related Questions