C# Remove from a collection after comparing another collection.

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
{
    public int Id { get; set; }
    public string Title { get; set; }
}

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>
                         {
                             new Record {Id = 1, Title = “Record1″},
                             new Record {Id = 1, Title = “Record1″},
                             new Record {Id = 2, Title = “Record2″},
                             new Record {Id = 3, Title = “Record3″}
                         };

var secondaryRecords = new List<Record>
                           {
                               new Record {Id = 1, Title = “Record1″},
                               new Record {Id = 4, Title = “Record4″},
                               new Record {Id = 5, Title = “Record5″}
                           };

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;
using System.Linq;

// HashSet is used to eliminate duplicate records from primary record
var recordIds = new HashSet<int>(primaryRecords.Select(r => r.Id));

// remove records that also exist in recordsId
secondaryRecords.RemoveAll(r => recordIds.Contains(r.Id));

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.

About these ads


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.