如何将Hashtable的密钥与Value交换

时间:2013-03-26 09:54:35

标签: c# .net hashtable

我已经通过以下方式解决了这个问题。 由于它很长,我需要一个更好的。

//代码

class Program
{
    static void Main(string[] args)
    {
        Hashtable hsTbl = new Hashtable();

        hsTbl.Add(1, "Suhas");
        hsTbl.Add(2, "Madhuri");
        hsTbl.Add(3, "Om");
        List<object> keyList = new List<object>();
        List<object> ValList = new List<object>();

        Console.WriteLine("Key          Value");
        foreach (DictionaryEntry item in hsTbl)
        {
            Console.WriteLine(item.Key + "      " + item.Value);
            keyList.Add(item.Value);
            ValList.Add(item.Key);

        }
        hsTbl.Clear()

//Swapping          

        for (int i = 0; i < keyList.Count; i++)
        {
            hsTbl.Add(keyList[i], ValList[i]);
        }

//will display hashtable after swapping

        foreach (DictionaryEntry item in hsTbl)
        {
            Console.WriteLine(item.Key + "      " + item.Value);
        }
    }
}

还有其他更好的解决方案吗?

2 个答案:

答案 0 :(得分:1)

你可以使用额外的数组和CopyTo方法而不是2个列表稍微简单一些,但不创建额外的HashTable,如下所示:

//代码

using System;
using System.Collections;

class Program
{
  static void Main()
  {
      Hashtable hsTbl = new Hashtable();

      hsTbl.Add(1, "Suhas");
      hsTbl.Add(2, "Madhuri");
      hsTbl.Add(3, "Om"); 

      DictionaryEntry[] entries = new DictionaryEntry[hsTbl.Count];
      hsTbl.CopyTo(entries, 0);
      hsTbl.Clear();

      foreach(DictionaryEntry de in entries) hsTbl.Add(de.Value, de.Key);

      // check it worked

      foreach(DictionaryEntry de in hsTbl)
      {
         Console.WriteLine("{0} : {1}", de.Key, de.Value);
      }
  }
}

请注意,通常情况下,不保证任何方法都能正常工作,因为原始哈希表中的某些值可能会重复,因此不适合作为键。

答案 1 :(得分:1)

您可以使用通用Dictionary<string,int>,这很容易使用Linq创建:

var dictionary = hsTbl.OfType<DictionaryEntry>()
                      .ToDictionary(e => (string)e.Value, e => (int)e.Key);

如果您真的需要Hashtable,那么:

Hashtable table = new Hashtable();
foreach (DictionaryEntry entry in hsTbl)
    table.Add(entry.Value, entry.Key);

但是如果你想交换值和密钥,请确保所有值都是唯一的。