tags:

views:

99

answers:

3

I have an object which is contained within a List<>, I need to remove these from another List<>

e.g.

List<MyObject> AllElements = new List<MyObject>();
List<MyObject> SearchResults = new List<MyObject>();

... Do something so that SearchResults contains a subset of the objects contained within AllResults

Currently I do this to delete them from the main list:

for(int i = 0; i < SearchResults.Count; i++) 
    AllElements.Remove(SearchResults[i]); 

Is there an nicer [linqier!] way?

+5  A: 

IEnumerable<T>.Except is your friend (if I'm reading your example correctly):

allElements = allElements.Except(searchResults);
Justin Niessner
+10  A: 

You can use the Enumerable.Except Method (from MSDN)

List<MyObject> FilteredElements = AllElements.Except(SearchResults).ToList();

Alison
You'll need to tag a `ToList` call on the end if you want the result to be a `List<MyObject>` rather than `IEnumerable<MyObject>`.
LukeH
+2  A: 

The following will give you a 'list' where everything in SearchResults was removed.

var results = AllElements.Where(i => !SearchResults.Contains(i));

You could then do:

AllElements = results.AsList();
jjnguy
Is there a benefit to using Where/Contains as to simply using Except?
Justin Niessner
@Justin, the benefit for me was that I knew about the `Where()` way to do it. I had no idea you could use `Except()`. I posted my answer at the same time as your, and I'm gonna leave it up because it is right, and it is good to know other ways to do things.
jjnguy
@Justin(s): There is a semantic difference between them as well. `Except` produces the set difference of the two sequences which means that any duplicates are also removed. For example, if the two sequences are `{ 1, 2, 3, 5, 1, 2, 4 }` and `{ 3, 4 }` then using `Except` will give you the sequence `{ 1, 2, 5 }` whereas using `Where`/`Contains` will give you `{ 1, 2, 5, 1, 2 }`.
LukeH
@Luke, interesting, thanks for the info.
jjnguy