i've 2 dictionaries like:
dictionary<string, object> dict1 = new dictionary<string, object>(); dictionary<string, object> dict2 = new dictionary<string, object>(); i want compare them few entries list<enum>, how can compare these list<enum> objects. please see following sample code:
enum days { monday, tuesday, wednesday } enum colors { red, green, blue } enum cars { acura, bmw, ford } populating dictionaries:
list<days> lst1 = new list<days>(); list<days> lst2 = new list<days>(); lst1.add(days.monday); lst1.add(days.tuesday); lst2.add(days.monday); lst2.add(days.tuesday); dict1.add("dayenum", lst1); dict2.add("dayenum", lst2); foreach (keyvaluepair<string, object> entry in dict1) { var t1 = dict1[entry.key]; var t2 = dict2[entry.key]; if (dict1[entry.key].gettype().isgenerictype && compare(dict1[entry.key], dict2[entry.key])) { // list elements matches... } else if (dict1[entry.key].equals(dict2[entry.key])) { // other elements matches... } } it doesn't match unless provide exact enum i.e. ienumerable<days> need generic code work enum.
so far found following way compare, need generic comparision statement don't know enums:
private static bool compare<t>(t t1, t t2) { if (t1 ienumerable<t>) { return (t1 ienumerable<t>).sequenceequal(t2 ienumerable<t>); } else { type[] generictypes = t1.gettype().getgenericarguments(); if (generictypes.length > 0 && generictypes[0].isenum) { if (generictypes[0] == typeof(days)) { return (t1 ienumerable<days>).sequenceequal(t2 ienumerable<days>); } else if (generictypes[0] == typeof(colors)) { return (t1 ienumerable<colors>).sequenceequal(t2 ienumerable<colors>); } } return false; } }
first type of generic arguments type.getgenericarguments(), can call isenum on that.
so,
var listtype = dict1[entry.key].gettype(); if (listtype.isgenerictype) { var typearguments = listtype.getgenericarguments(); //if have list<t> in there, can pull first 1 var generictype = typearguments[0]; if (generictype.isenum) { // list elements matches... } } in answer comment, if want compare 2 lists, can following. because have lists object in dictionary, you're better of creating own method check whether each element same element in other list, because sequenceequal have know type.
var listtype = dict1[entry.key].gettype(); var secondlisttype = dict2[entry.key].gettype(); if (listtype.isgenerictype && secondlisttype.isgenerictype) { //if have list<t> in there, can pull first 1 var generictype = listtype.getgenericarguments()[0]; var secondgenerictype = secondlisttype.getgenericarguments()[0]; if (generictype.isenum && generictype == secondgenerictype && areequal((ilist)dict1[entry.key],(ilist)dict2[entry.key])) { // list elements matches... } } public bool areequal(ilist first, ilist second) { if (first.count != second.count) { return false; } (var elementcounter = 0; elementcounter < first.count; elementcounter++) { if (!first[elementcounter].equals(second[elementcounter])) { return false; } } return true; }
Comments
Post a Comment