I have a nested public class KeyCountMap
public KeyCountMap<T> { private IDictionary<T, MutableInt> map = new Dictionary<T, MutableInt>(); public KeyCountMap() { } public KeyCountMap(Type dictionaryType) { if (!typeof(IDictionary<T, MutableInt>).IsAssignableFrom(dictionaryType)) { throw new ArgumentException("Type must be a IDictionary<T, MutableInt>", "dictionaryType"); } map = (IDictionary<T, MutableInt>)Activator.CreateInstance(_dictionaryType); } public HashSet<KeyValuePair<T, MutableInt>> EntrySet() { return map.ToSet(); }
To sort the values ββon the map in descending order of values, if we use Java, we can write a method like:
public static <T> KeyCountMap<T> sortMapByDescendValue(KeyCountMap<T> map) { List<Entry<T, MutableInt>> list = new LinkedList<>(map.entrySet()); Collections.sort(list, new Comparator<Entry<T, MutableInt>>() { @Override public int compare(Entry<T, MutableInt> o1, Entry<T, MutableInt> o2) { return (-1) * (o1.getValue().get()).compareTo(o2.getValue().get()); } }); KeyCountMap<T> result = new KeyCountMap<T>(); for (Entry<T, MutableInt> entry : list) { result.put(entry.getKey(), entry.getValue()); } return result; }
If we use C #, we can define the method as:
public static KeyCountMap<T> SortMapByDescendValue<T>(KeyCountMap<T> map) { List<KeyValuePair<T, MutableInt>> list = new List<KeyValuePair<T, MutableInt>>(map.EntrySet());
Will this method work, or do I need to override the CompareTo() method (not used here) for sorting?
EDIT
public class MutableInt { internal int _value = 1;
sorting dictionary c # value
maliks Jun 14 '16 at 11:58 2016-06-14 11:58
source share