Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
how do i filter out the common elements of two lists?
Posted
Comments
Kenneth Haugland 26-Sep-15 1:58am    
Linq would be the easiest way I could think of
Sergey Alexandrovich Kryukov 26-Sep-15 6:14am    
First of all, why not making sure that you don't add duplicates in first place? Anyway, What have you tried so far?
—SA
BillWoodruff 26-Sep-15 6:56am    
Do you mean you want to remove items that are in both lists ? Or do you mean you want to create a new List that contains only the items not in both lists ?

Use Enumerable.Intersect[^].

Example is on the page.
C#
IEnumerable<Product> duplicates = store1.Intersect(store2);
 
Share this answer
 
If you want the values which are in both lists:
C#
var inBoth = firstList.Intersect(secondList);

If you want the values which are in the first list, but not the second:
C#
var inFirst = firstList.Except(secondList);

If you want the values which are not common to both lists:
C#
var notInBoth = firstList.Except(secondList).Union(secondList.Except(firstList));
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900