Let’s assume I have 2 List<T> List1 and List2 that look like this:
List 1:
[ID:1, Name:"item1"]
[ID:2, Name:"item2"]
[ID:3, Name:"item3"]
[ID:4, Name:"item4"]
List 2:
[ID:2, Name:"item2"]
[ID:3, Name:"item3"]
[ID:5, Name:"item5"]
[ID:6, Name:"item6"]
How can I get a list that contains only the objects that are in both lists? Using the example above, I want to return:
[ID:2, Name:"item2"]
[ID:3, Name:"item3"]
Modifying the original lists is OK. What’s the best way to do this?
Is the most succinct. However keep in mind it is using the default equality comparer which may or may not work for you. If not, you can provide your own: