C #: merging two duplicate excluded lists

What is a simple, efficient way to take List2 and add it to the end of List1, but in such a way that only those elements that are not already in List1 before concatenation are added to it?

EDIT: I tried to use the methods suggested in the answers here, but I still get the cheats added to List1!

This is a sample code:

// Assume the existence of a class definition for 'TheObject' which contains some 
// strings and some numbers.

string[] keywords = {"another", "another", "another"};
List<TheObject> tempList = new List<TheObject>();
List<TheObject> globalList = new List<TheObject>();

foreach (string keyword in keywords)
{
    tempList = // code that returns a list of relevant TheObject(s) according to
               // this iteration keyword.
    globalList = globalList.Union<TheObject>(tempList).ToList();
}

When debugging - after the second iteration - globalList contains two copies of the same TheObject. The same thing happens when you try to implement the decision of Edward Bray ...

EDIT2:
, tempList, , globalList ( ! GlobalList.contains()) - .

, ...

+3
3

List Union,

List1.Union(list2);
+2

LINQ Union , List1 . , , O (m * n), - ( T ):

var intersection = new HashSet<T>(List1.Intersect(List2));
List1.AddRange(List2.Where(item => !intersection.Contains(item)));
+1

All Articles