c# - Keep differences between two hashtables -
i making function compares 2 hashtables , want keep difference of these tables. if both contain 100 keys , 2 have been altered want new hashtable equal 2 differences.
here have. lost on how (keep differences)
private hashtable comparehashtables(hashtable ht1, hashtable ht2) { hashtable resultsofcompare = new hashtable(); foreach (dictionaryentry entry in ht1) { if (ht2.containskey(entry.key) && ht2.containsvalue(entry.value) == false) { //keep differences } } return resultsofcompare; }
it seems want check both key , value equality. if both don't match it's considered difference. creates bit of problem because type of difference can't represented in hash table. consider following
- ht1: key =
"bob"
value =42
- ht2: key =
"bob"
value =13
here key same value difference. store every difference resulting structure need able contain 2 different values same key. that's not possible hashtable
. arraylist
of entries differ may better choice exercise.
really there 3 cases consider
- both tables contain same key have different values
- left table has key not right
- right table has key not left
items 2 , 3 can collapsed it's harder collapse 1 bag. need data structure instruct difference in table
struct difference { internal readonly bool isvaluedifferent; internal readonly object key; internal readonly object value; internal readonly object othervalue; internal difference(object key, object value) { key = key; value = value; isvaluedifferent = false; } internal difference(object key, object value, object othervalue) { key = key; value = value; othervalue = othervalue; isvaluedifferent = true; } }
with can represent cases.
private hashtable comparehashtables(hashtable ht1, hashtable ht2) { arraylist difflist = new arraylist(); foreach (dictionaryentry entry in ht1) { object value = ht2[entry.key]; if (value == null) { difflist.add(new difference(entry.key, entry.value)); } else if (!value.equals(entry.value)) { difflist.add(new difference(entry.key, entry.value, value)); } } foreach (dictionaryentry entry in ht2) { object value = ht1[entry.key]; if (value == null) { difflist.add(new difference(entry.key, entry.value)); } } return difflist; }
note: hashtable
, arraylist
deprecated @ point. why not use dictionary<tkey, tvalue>
, list<t>
instead?
Comments
Post a Comment