Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq List<string> union

Tags:

c#

linq

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");
like image 540
Anthony Avatar asked Aug 23 '09 09:08

Anthony


People also ask

What does Union do in Linq?

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.

How do you write a Union query in Linq?

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.

Is the Union method gets the unique elements from both the lists?

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.


2 Answers

var items = list1.Intersect(list2);

See also:

  • Intersect
  • Much recommended: 101 LINQ Samples
like image 179
Kobi Avatar answered Sep 19 '22 23:09

Kobi


I know LINQ was tagged, but just for completeness; if LINQ isn't an option;

List<string> result = list1.FindAll(list2.Contains);
like image 41
Marc Gravell Avatar answered Sep 20 '22 23:09

Marc Gravell