A good way to combine two <T> s lists in .NET 2.0?

I have two lists in which I need to form a union, but I'm in .NET 2.0, so the Union () method seems to be missing. These are lists of integers, so no problem with comparing equalities. What a good way to do this?

+4
source share
4 answers

How about (using dictionary keys as a hash table):

public static List<T> Union<T>(List<T> first, List<T> second) { List<T> newList = new List<T>(first.Count + second.Count); Dictionary<T, object> firstItems = new Dictionary<T, object>(first.Count); foreach (T item in first) { newList.Add(item); firstItems.Add(item, null); } foreach (T item in second) { if (!firstItems.ContainsKey(item)) { newList.Add(item); } } return newList; } 

This will maintain the order of the positions in first and second , while at the same time using the O (1) check to duplicate items between lists

+3
source

You can simply add them together and remove duplicates:

  public List<T> Union<T>(List<T> firstList, List<T> secondList) { Dictionary<T, int> tmp = new Dictionary<T, int>(); foreach (T val in firstList) { tmp[val] = 1; } foreach (T val in secondList) { tmp[val] = 1; } return new List<T>(tmp.Keys); } 
+3
source

How about a simple foreach by only adding elements that are not yet in the list:

 foreach (int item in list2) { if (!list1.Contains(item)) { list1.Add(item); } } 

This will preserve the order of the lists.

+1
source

You can use linqbridge so you can use LINQ to Objects while still targeting Framework 2.0 if you have Visual Studio 2008.

And click, click, click to go to .NET 3.5. LINQ and lambdas change the way you think about code (for the better, IMHO).

+1
source

All Articles