代码如下,dic_add是需要修改到文件里面的内容,hashTable里面是要修改的内容,有时候要修改的东西太多,就会导致速度很慢,而且如果处理的文件很大的话,貌似很占内存,如何处理,使其速度加快,谢谢
private Hashtable addCom(Dictionary<string,string> dic_add,List<string> list_add,Hashtable hashTable)
{
string partreference = string.Empty;
string partNumber = string.Empty;
string temp = string.Empty;
string strtemp = string.Empty;
List<string> alist = new List<string>();
string property = "property";
Func<string,string,bool> lambda = IsContainNum();//此方法是判断是否存在这个字符串的
foreach(KeyValuePair<string,string> item in dic_add)
{
partrefence = item.Key;
partNumber = item.Value;
temp = @"(property PART_NUMBER" +"\r\n"+@"(string"+"\""+partrefence+"\""+"))";
strtemp = "stringDisplay"+"\""+partrefence+"\"";
foreach(object hashItem in new ArrayList(hashTable.Keys))
{
if(hashItem.Equals(partreference))
{
string addtemp = hashTable[hashItem].ToString();
string[] addList = addtemp.Split(new string[]{"\r\n"},StringSplitOptions.RemoveEmptyEntries);
alist.AddRange(addList);
foreach(string str_item in alist)
{
if(lambda(str_item,property))
{
alist.Insert(alist.IndexOf(str_item),temp);
hashTable[hashItem] ="";
foreach(string colTemp in alist)
{
hashTable[hashItem]+= colTemp+"\r\n";
}
break;
}
}
alist.Clear();
break;
}
}
}
return hashTable;
}
------解决思路----------------------
string addtemp = hashTable[hashItem].ToString();
string[] addList =
循环内,不要定义变量
定义在循环外,内部只操作变量 .
------解决思路----------------------
foreach(object hashItem in new ArrayList(hashTable.Keys))
{
if(hashItem.Equals(partreference))
{
string addtemp = hashTable[hashItem].ToString();
这个循环可以去掉,直接判断hash表是否有这个键就行了,hash表的键不可能有重复的吧
if(hashTable.Contains(hashItem))
{
string addtemp = hashTable[hashItem].ToString();
}
还有很多地方可优化,等下贴一份改过代码给你
------解决思路----------------------
Hashtable resultHashTable = (Hashtable)hashTable.Clone();//拷贝一个副本,避免直接修改传入的哈希表
核心循环中更改这个副本哈希表:
resultHashTable[partrefence] = ""; //I do
foreach (string colTemp in alist)
{
resultHashTable[partrefence] += colTemp + "\r\n"; //I do
}
最后直接返回这个副本哈希表
return resultHashTable;