日期:2014-05-18  浏览次数:20435 次

Hashtable怎样根据Key取value
U0015Model.cs
public class U0015Model
  {
  public Hashtable SelectDate(string year)
  {  
  string hql1 = "select distinct a.Bcscalmouth from Bcscalendar a where a.Bcscalyear='"+year+"' and a.Bcscalisrest='1'";
  string hql2 = "select a.Bcscalday from Bcscalendar a where a.Bcscalyear='"+year+"' and a.Bcscalisrest='1'";

  BCSDB db = new BCSDB();

  IList list1 = db.selectHql(hql1);
  IList list2 = db.selectHql(hql2);
  Hashtable ht = new Hashtable();
  ht.Add(list1,list2);

  return ht;
  }
  }

  U0015.aspx.cs
  protected void receive(int year,int month)
  {
  U0015Model u0015 = new U0015Model();
  Hashtable ht = new Hashtable();
  ht = u0015.SelectDate(ddlstSelectYear.SelectedValue);
  object obj = ht["01"];
  }
在U0015Model.cs中从数据库中取出数据,放到Hashtable里.现在Key为"01","02",如何根据键值取出对应的Value?

------解决方案--------------------
Hashtable hashtable = new Hashtable();
hashtable.Add("1", "1001");
Response.Write(hashtable["1"]);


结果为:1001
------解决方案--------------------
就这样呗:ht["01"]
不过取出来的是object类型,你还要进行类型转换
------解决方案--------------------
探讨
但是我用string s=Convert.ToString(ht["01"]);这条语句取不到值

------解决方案--------------------
Hashtable table = new Hashtable();
table.Add(1, "001");
table.Add(2, "002");
table.Add(3, "003");
table.Add(4, "004");

foreach (System.Collections.DictionaryEntry entry in table)
{
Console.WriteLine("Key: " + entry.Key.ToString() + " Vlaue: " + entry.Value.ToString());
}

这样的话就可以取到里面所有的key和value了。

还有,你在HashTable中增加了两个IList,当其中的一个做为key的时候,你要知道这个IList是怎么去比较的。
还有你要看看IList中的.equals()方法是怎么判定的。要不然你肯定不会拿到你想要的值的。