A good way to combine two <T> s lists in .NET 2.0?
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
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
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