|
|
Blog entries in category
"Java"
shown here:
See other entries in category : Whateveah | Java | All |
C# and SubMaps
It took me a while to figure out why my C# code wasnt working as expected today. After much debugging it turned out that C# doesnt have a clean SubMap implementation, or least one that I could find. What I was assuming will work wasnt quite cutting it.In Java you can easily get a subMap using string keys based on a regular expression magically. For example the code, Prints out something like...TreeMapsortedMap = new TreeMap (); for(int i = 0;i<10;i++) sortedMap.put("SomeKey_"+i, "SomeValue"); System.out.println(sortedMap); String low = "SomeKey_3", high = "SomeKey~"; System.out.println(low); System.out.println(high); {SomeKey_0=SomeValue, SomeKey_1=SomeValue, SomeKey_2=SomeValue, SomeKey_3=SomeValue, SomeKey_4=SomeValue, SomeKey_5=SomeValue, SomeKey_6=SomeValue, SomeKey_7=SomeValue, SomeKey_8=SomeValue, SomeKey_9=SomeValue} SomeKey_3 SomeKey~ {SomeKey_3=SomeValue, SomeKey_4=SomeValue, SomeKey_5=SomeValue, SomeKey_6=SomeValue, SomeKey_7=SomeValue, SomeKey_8=SomeValue, SomeKey_9=SomeValue}
The closest way of doing this in C# is a bit of a hack using the System.Collections.SortedList and the Comparer classes and its specific to what I was trying to do.I replace the regex ~ with a series of 9's.
public static SortedList SubMap(SortedList list, System.Object lowerLimit, System.Object upperLimit) {
string upperStr = upperLimit.ToString();
if (upperStr.EndsWith("~"))
upperLimit = upperStr.Replace("~", "999999999999999");
Comparer comparer = Comparer.Default;
SortedList newList = new SortedList();
if (list != null){
if ((list.Count > 0) &&(comparer.Compare(lowerLimit,upperLimit) <1)){
int index = 0;
while (comparer.Compare(list.GetKey(index), lowerLimit) < 0)
index++;
for (; index < list.Count; index++){
if (comparer.Compare(list.GetKey(index), upperLimit) > 0)
break;
newList.Add(list.GetKey(index), list[list.GetKey(index)]);
}
}
}
return newList;
}
Certainly not clean but its all I can think of right now. For all the C# code floating on the web I couldnt find a SubMap implementation that does what the J2SE classes do. Anyone have any better ideas ?
( Mar 25 2006, 03:31:39 AM EST )
Permalink
Comments [0]
Trackback URL: http://blogs.sun.com/sameert/en/entry/c_and_sorted_submaps
Comments:
Post a Comment:

