排序自定义类字典C# [英] Sorting custom class dictionary C#

查看:158
本文介绍了排序自定义类字典C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套的公共类KeyCountMap

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();
   }  
   //... rest of the methods...
}

要以值的降序排列地图中的值,如果我们使用Java,我们可以将方法写为:

To sort out the values in map in descending order of values, if we use Java we can write method as:

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#,我们可以将方法定义为:

If we use C#, we can defined method as:

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()方法(这里不用)排序?

Will this method work or is it necessary to override CompareTo() method (not used here) for sorting?

编辑

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;
   }
}


推荐答案

字典(哈希表)没有订单。尝试通过控制插入顺序来排序哈希集不会奏效。如果您想订购,请勿使用字典作为后备店。

Dictionaries (hashtables) don't have an order. Trying to order a hashset by controlling the order of insertion just won't work. If you want ordering, don't use a dictionary as your backing store.

这篇关于排序自定义类字典C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆