Question

I have two Hashtables.

I'm trying to get the union, intersection and difference but how can I loop and compare between these two hashtables (hashtable1.Count is not equal hashtable2.Count), does anyone know how to do it with linq ?

public Hashtable operator +(Hashtable g1, Hashtable g2) //union
    {
        Hashtable result = new Hashtable();
        //loop
        {
            if(!result.Contains(g1[i]))
            {
                result.Add(g1[i]);
            }
            if(!result.Contains(g2[i]))
            {
                result.Add(g2[i]);
            }
        }
        return result;
    }
    public Hashtable operator -(Hashtable g1, Hashtable g2) //intersection 
    {
        Hashtable result = new Hashtable();
        //loop
        {
            if (g1[i] == g2[i])
            {
                result.Add(g1[i]);
            }
        }
        return result;
    }
    public Hashtable operator /(Hashtable g1, Hashtable g2) //difference 
    {
        Hashtable result = new Hashtable();
        //loop
        {
            if (g1[i] != g2[i])
            {
                result.Add(g1[i]);
            }
        }
        return result;
    }
Was it helpful?

Solution

Well, it's gonna be rather hard to use IEnumerable<T> extensions methods if you use an Hashtable instead of a Dictionary<TKey, TValue>.

Because an Hashtable is not a generic type.

So there's no Hashtable.Union available, nore Hashtable.Keys.Union.

You would have to do something like

hashtable1.Keys.Cast<int>().Union(hashtable2.Keys.Cast<int>());

But... what will happen if keys are not int ?

If you change Hashtable to Dictionary<TKey, TValue>, you'll be able to do things like

var resultDictionary = dic1.Intersects(dic2).ToDictionary(m => m.Key, m => m.Value);

var resultDictionary = dic1.Except(dic2).ToDictionary(m => m.Key, m => m.Value);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top