C# Remove from a collection after comparing another collection.
Posted: 10/02/2012 Filed under: Programming | Tags: C# Leave a comment »This post shows you how it’s possible to compare two list collections and remove items/object when they do not match.
I have, for the purpose of this post, created a simple Record entity.
|
class Record |
Now I instantiate some record objects, and add them to two separate collections. Note how primaryRecords has duplicate objects of Record1? Also, note that secondaryRecords also has an object of Record1.
|
var primaryRecords = new List<Record> var secondaryRecords = new List<Record> |
Now, I compare my secondaryRecords and my primaryRecords to ensure that only unique records within the secondaryRecords is made available.
This is first accomplished by getting unique record objects from primaryRecords, which is achieved through the use of a HashSet<> object with little bit of lambda sprinkled in.
|
using System.Collections.Generic; // HashSet is used to eliminate duplicate records from primary record // remove records that also exist in recordsId |
A console output of enumerating and displaying secondaryRecords would be as below.
| Record4 Record5 |
Hope this helps you in moments of madness dealing with multiple collections.