Compare two general lists and remove duplicates

I have two general lists, one called “Favorite” and the other “Filtered”.

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

Both contain Content elements, which are simple classes:

 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 displayed in Filtered but also displayed in Favorites should be removed from Filtered. In addition, both lists will be merged into one general list with the "Favorites" items that appear first.

I know that I could write a couple of foreach loops to do this, but I cannot help but feel that there should be a more elegant method using LINQ.

I am using C # 4.0.

+6
source share
3 answers

If you have IEqualityComparer installed, 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(); } } 
+6
source

Are you looking for a LINQ Union method, specifically

 var singleList = Featured.Union(Filtered); 

This will return all Featured elements followed by all Filtered elements that were not Featured . Note that it will also remove any duplicates in the list - so if the Featured item is twice, it will be displayed only once.

However, you must be able to compare instances of Content in order to do this by adding Equal and GetHashCode in the implementation, or by providing IEqualityComparer .

+6
source

Assuming that the presenting object in both lists is the same objects, you can do the following:

 var totalList = Featured .Concat(Filtered.Where(f => !Featured.Contains(f))) .ToList() 

Update

Or, using the Except method mentioned by Mahmoud Gamal:

 var totalList = Featured .Concat(Filtered.Except(Featured)) .ToList() 
+2
source

Source: https://habr.com/ru/post/920036/


All Articles