日期:2014-05-17  浏览次数:20530 次

Hashtable循环遍历问题
Hashtable ht = (Hashtable)Session["UserList"];
我想循环遍历我的hashtabale中的key值,然后循环遍历出来,用string接收,出现这种效果,如果为1个,则只是1,如果多个则用,隔开,形成这样的效果1,2,3

------解决方案--------------------
string result = "";
if (ht.Count == 1)
result = ht[0].ToString();
else
{
for (int i = 0; i < ht.Count; i++)
{
if (i == ht.Count - 1)
{
result += ht[i].ToString()
}
else
{
result += ht[i].ToString() + ",";
}
}
}
------解决方案--------------------
C# code
 Hashtable ht = new Hashtable();
                ht.Add("1t", "1");
                ht.Add("2t", "1");
                StringBuilder sb = new StringBuilder();
                foreach (var item in ht.Keys)
                    sb.Append(item.ToString()+",");
                string result = sb.ToString().TrimEnd(',');//1t,2t

------解决方案--------------------
string str = string.Join(",", ht.Cast<DictionaryEntry>().Select((key, value) => value.ToString()).ToArray());