How can I use Linq to find common items between 2 generic lists of type string.
For example, say I have the following code, I would like to get a List < string> which would contain item2 and item3:
List<string> List1 = new List<string>();
List<string> List2 = new List<string>();
List1.Add("item1");
List1.Add("item2");
List1.Add("item3");
List2.Add("item2");
List2.Add("item3");
List2.Add("item4");
Introduction to LINQ Union. LINQ Union is used to retrieve the distinct elements between two collections/ sequences; it combines two or more collections of elements and finally returns the unique elements as a result.
LINQ Union operator is used for finding unique elements between two sequences (Collections). For example, suppose we have two collections A = { 1, 2, 3 }, and B = { 3, 4, 5 }. Union operator will find unique elements in both sequences. { 3 } element is available in both sequences.
Union is an extension method to merge two collections. It requires at least two collections to perform the merge operation, but that merged collection holds only the distinct elements from both the collections.
var items = list1.Intersect(list2);
See also:
Intersect
I know LINQ was tagged, but just for completeness; if LINQ isn't an option;
List<string> result = list1.FindAll(list2.Contains);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With