【发布时间】:2016-10-15 03:32:49
【问题描述】:
我有一个嵌套的公共类 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();
}
//... rest of the methods...
}
为了将map中的值按值降序排列,如果我们使用Java我们可以这样写:
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;
}
如果我们使用C#,我们可以将方法定义为:
public static KeyCountMap<T> SortMapByDescendValue<T>(KeyCountMap<T> map)
{
List<KeyValuePair<T, MutableInt>> list = new List<KeyValuePair<T, MutableInt>>(map.EntrySet());
// map.EntrySet() returns of type HashSet<KeyValuePair<T, MutableInt>>
list = list.OrderByDescending(x => x.Value).ToList();
KeyCountMap<T> result = new KeyCountMap<T>();
foreach (KeyValuePair<T, MutableInt> entry in list)
{
result.Put(entry.Key, entry.Value);
}
return result;
}
此方法是否有效,或者是否有必要覆盖CompareTo() 方法(此处未使用)进行排序?
编辑
public class MutableInt
{
internal int _value = 1; // note that we start at 1 since we're counting
public void Increment()
{
_value++;
}
public void Discrement()
{
_value--;
}
public int Get()
{
return _value;
}
}
【问题讨论】:
-
字典不能保证按照插入的顺序返回项目,因此您在那里尝试执行的操作可能行不通。
-
那么如何解决这个问题,即对字典进行排序?
-
请看
SortedDictionary<K,V> -
我在课堂上有
IDictionary而不是SortedDictionaryKeyCountMap<T> -
@DmitryBychenko 如果我在
KeyCountMap<T>类中使用SortedDictionary而不是IDictionary那么是否需要编写类似SortMapByDescendValue()的方法?
标签: c# sorting dictionary