I have two lists I need to form the union of, but I'm in .NET 2.0 so the Union() method appears to be out. These are lists of integers, so no problem with the equality comparisons. What's a good way to go about this?
What about (using Dictionary keys as a hashtable):
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 item order in first
and second
, while still using an O(1) check for duplicate items between the lists
You could just add them together and remove the 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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With