为什么我嵌套的for-if循环在嵌套时会加载很多? 我能解决这个问题吗?

对不起,如果问题有点模糊,但代码非常复杂,我希望你有正确的眼睛看到和理解它:)

我将显示2个sorting代码。 代码只是读取Excel表格,并根据它包含的文本,将它们放在一个列表中。 例如:我有一个excel表格:

A1 = Peter D1 = hello

A2 = Frank D2 = bye

A3 = Jan D3 = hello

A4 = Obama D4 = hello

HELLO列表将包含:D1,D3,D4列表BYE将包含:D2

我第一次有这个代码来做它运行得非常快:

 List<string> ARowList = new List<string>(); List<string> DRowList = new List<string>(); List<string> HELLO = new List<string>(); List<string> BYE = new List<string>(); List<List<string>> AllMeetingsLists = new List<List<string>>(); AllMeetingLists.Add (HELLO); AllMeetingLists.Add (BYE); for (int i = 1; !endReach; i++) { if (excel_getValue("D"+i).Contains("HELLO")) { HELLO.Add(excel_getValue("A"+1) + "said hello how are you") } else if (excel_getValue("D"+i).Contains("BYE")) { BYE.Add(excel_getValue("A"+1) + "said goodbye have a nice day") } Console.WriteLine(excel_getValue("A" + i)); //This goes on for 30 more options of what it can contain } 

我做了这个让它less代码,但这个运行速度慢得多:

 List<string> ARowList = new List<string>(); List<string> DRowList = new List<string>(); List<string> HELLO = new List<string>(); List<string> BYE = new List<string>(); List<List<string>> AllMeetingsLists = new List<List<string>>(); AllMeetingLists.Add (HELLO); AllMeetingLists.Add (BYE); List<string> ListWithAllSayings = new list<string>(); ListWithAllSayings.Add("hello"); ListWithAllSayings.Add("bye"); for (int j=0;j<ListWithAllSayings.Count;j++) { if (excel_getValue("D" +1).Contains(ListWithAllSayings[j])) { AllMeetingLists[j].Add("said hello/goodbye: ("A" +i)") // I have to make anther lists off what will be added with the ("A" + i) BUT this is NOT the problem } Console.WriteLine(excel_getValue("A" + i)); } 

这比其他代码运行速度慢。虽然这个代码更容易改变,而且更短。 (我怎样才能解决这个问题?

发生这种情况是因为ifthenelse的链if你find正匹配就会终止,而你的循环继续尝试其他的string。 如果您在大多数时间内的前几个常量匹配中find正确的值,则差异可能是显着的。

在find第一个项目时添加一个break可以解决这个问题。

你应该做的另一件事是将获得单元格的expression式移出循环。 您还应该将打印excel_getValue("A" + i)移出循环,因为在修改后的代码中,它将在嵌套循环的每次迭代中打印出来。

 var valueAtDi = excel_getValue("D" +i); for (int j=0;j<ListWithAllSayings.Count;j++) { if (valueAtDi.Contains(ListWithAllSayings[j])) { AllMeetingLists[j].Add("said hello/goodbye: ("A" +i)"); break; } } Console.WriteLine(excel_getValue("A" + i));