Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two generic lists and remove duplicates

Tags:

c#

linq

I have two generic Lists, one called "Featured" and the other called "Filtered".

List<Content> Featured = new List<Content>();
List<Content> Filtered = new List<Content>();

Both contain "Content" items which are simple classes like so :

public class Content
{
    public long ContentID { get; set;}
    public string Title { get; set; }
    public string Url { get; set; }
    public string Image { get; set; }
    public string Teaser { get; set; }

    public Content(long contentId, string title, string url, string image, string teaser)
    {
        ContentID = contentId;
        Title = title;
        Url = url;
        Image = image;
    }
}

Any items that appear in "Filtered" but also appear in "Featured" need to be removed from "Filtered". Additionally, both lists will then be combined into a single generic list with the "Featured" items appearing first.

I know I could write a couple of foreach loops to do this but I can't help feel there must be a more elegant method using LINQ.

I am using C# 4.0.

like image 422
rf_wilson Avatar asked Jul 09 '12 13:07

rf_wilson


2 Answers

If you have an IEqualityComparer defined you can use the Union method:

List<Content> FeaturedAndFiltered = Featured.Union(Filtered, new MyContentComparer());

A rough implementation of MyContentComparer would be:

public class ContentEqualityComparer : IEqualityComparer<Content>
{

    public bool Equals(Content c1, Content c2)
    {
        return (c1.ContentID == c2.ContentID);
    }


    public int GetHashCode(Content c)
    {
        return c.ContentID.GetHashCode();
    }

}
like image 141
D Stanley Avatar answered Nov 04 '22 21:11

D Stanley


You're looking for the LINQ method Union, specifically

var singleList = Featured.Union(Filtered);

This will return all the Featured items, followed by all the Filtered items that were not Featured. Note that it will also remove any duplicates within a list - so if an item is Featured twice, it will only show up once.

You do, however, need to be able to compare instances of Content in order to do this, either by adding in implementations of Equal and GetHashCode or by providing an IEqualityComparer.

like image 34
Rawling Avatar answered Nov 04 '22 20:11

Rawling