Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good way to combine two List<T>s in .NET 2.0?

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?

like image 261
larryq Avatar asked Feb 28 '23 00:02

larryq


2 Answers

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

like image 190
thecoop Avatar answered Mar 07 '23 00:03

thecoop


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);
  }
like image 38
SwDevMan81 Avatar answered Mar 07 '23 00:03

SwDevMan81