Skip to content

Instantly share code, notes, and snippets.

@vgerbase
Last active June 15, 2020 15:02
Show Gist options
  • Save vgerbase/7be8e0230f47c030af7960ffe631d5f7 to your computer and use it in GitHub Desktop.
Save vgerbase/7be8e0230f47c030af7960ffe631d5f7 to your computer and use it in GitHub Desktop.
Simplest way to form a union of two lists

If it is a list, you can also use AddRange method.

var listB = new List<int>{3, 4, 5};  
var listA = new List<int>{1, 2, 3, 4, 5};
listA.AddRange(listB); // listA now has elements of listB also.

If you need new list (and exclude the duplicate), you can use Union.

var listB = new List<int>{3, 4, 5};  
var listA = new List<int>{1, 2, 3, 4, 5};
var listFinal = listA.Union(listB);

If you need new list (and include the duplicate), you can use Concat.

var listB = new List<int>{3, 4, 5};  
var listA = new List<int>{1, 2, 3, 4, 5};
var listFinal = listA.Concat(listB);

If you need common items, you can use Intersect.

var listB = new List<int>{3, 4, 5};  
var listA = new List<int>{1, 2, 3, 4};  
var listFinal = listA.Intersect(listB); //3,4

https://stackoverflow.com/a/13505715

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment