如果不选择Hashtable,而采用类似功能的泛型Dictionary<string,string>,这个检索可以利用LINQ实现。应该会简便一些吧。大概象下面这样: Dictionary<string, string> ht1 = new Dictionary<string, string>(); ht1.Add("key_A", "value_A"); ht1.Add("key_B", "value_B"); ht1.Add("key_C", "value_C");Dictionary<string, string> ht2 = new Dictionary<string, string>(); ht2.Add("key_A", "value_D"); ht2.Add("key_B", "value_E"); ht2.Add("key_C", "value_F"); var result = from l in ht1 join r in ht2 on l.Key equals r.Key into temp from t in temp select new { Key = t.Key, Value = t.Key + '|' + l.Value + '|' + t.Value };foreach (var item in result) Console.WriteLine("{0}:{1}", item.Key, item.Value); 结果: key_A:key_A|value_A|value_D key_B:key_B|value_B|value_E key_C:key_C|value_C|value_F
foreach (DictionaryEntry de in ht1)
{
if (ht2.ContainsKey(de.Key))
{
msg += de.Key + " " + de.Value + " " + ht2[de.Key] + Environment.NewLine;
}
}
你是这个意思么?
System.Collections.HashTable ht1=new System.Collections.HashTable();
ht1.Add("key_A","value_A");
ht1.Add("key_B","value_B");
ht1.Add("key_C","value_C");
System.Collections.HashTable ht2=new System.Collections.HashTable();
ht2.Add("key_A","value_D");
ht2.Add("key_B","value_E");
ht2.Add("key_C","value_F");StringBuilder sb = new StringBuilder();foreach (System.Collections.DictionaryEntry item1 in ht1)
{
item.Key.ToString();//键
foreach (System.Collections.DictionaryEntry item2 in ht2)
{
if(item2.Key.ToString()==item1.Key.ToString())
{
sb.Append(item1.Key.ToString()+"/"+item1.Value.ToString()+"/"+item2.Value.ToString()+",");
}
}
}string s = sb.ToString().TrimEnd(',');
string[] ss = s.Split(',');
foreach(string sss in ss)
{
Response.Write(sss.ToString()+"<br/>");
}
但是,如果两个Hashtable都很大的话,效率很低
可以这样考虑:
新建一个hashtable storeTable,循环原来的一个hashtable A,
foreach(key in A)
{
storeTable.Add(key,1);//value 用来标记是那个hashtable的key,如1-A,2-B,3-AB
}
foreach(key in B)
{
if(storeTable.ContainsKey(key))
storeTable[key] = 3;//表示此key为AB hashtable共有
else
storeTable.Add(key,2);
}然后遍历storeTable,根据value值判断输出情况-----------------
用空间换取时间
不过提供的思路就是,要快就不是用两个hashtable,而是用一个能同时装下K + V1 + V2的容器,LZ可以考虑考虑。
Dictionary<string, string> ht1 = new Dictionary<string, string>();
ht1.Add("key_A", "value_A");
ht1.Add("key_B", "value_B");
ht1.Add("key_C", "value_C");Dictionary<string, string> ht2 = new Dictionary<string, string>();
ht2.Add("key_A", "value_D");
ht2.Add("key_B", "value_E");
ht2.Add("key_C", "value_F");
var result = from l in ht1
join r in ht2
on l.Key equals r.Key
into temp
from t in temp
select new { Key = t.Key, Value = t.Key + '|' + l.Value + '|' + t.Value };foreach (var item in result)
Console.WriteLine("{0}:{1}", item.Key, item.Value);
结果:
key_A:key_A|value_A|value_D
key_B:key_B|value_B|value_E
key_C:key_C|value_C|value_F