2017-04-26 130 views
0

我需要找到一個代碼,以便我可以從列表框中最小的數字中減去最大的數字。我添加列表框中的項目從屬性,如果有人知道什麼,請幫助我,我試過這個代碼如何計算列表框中的兩個數字

int lowestattendance = attenadances.Max(); 
    string lowestname = ""; 
    int index = 0; 

    while (index < attenadances.Count) ; 
    { 
     if (attenadances[index] < lowestattendance) 
     { 
      lowestattendance = attenadances[index]; 
      lowestname = Names[index]; 
     } 

     index++; 
    } 

    string message = string.Format(
    "the person with the lowest attendance is {0}" + "and his attendance is { 1}", 
     lowestname, 
     lowestattendance); 

    MessageBox.Show(message, " lowest attendance"); 

而且也從未表現出任何東西。

+3

您是否調試過您的代碼以查看發生了什麼?當你說「它從未展示過任何東西」時,你的意思是沒有出現信息框,或者它沒有顯示你認爲的信息? –

+0

'attenadances'是什麼?它是列表框控件的名稱嗎? – RBT

回答

0

您正在尋找ArgMin功能;即使的LINQ沒有這樣的事情,你可以很容易地與Aggregate幫助實現它:

using System.Linq; 

    ... 

    //TODO: typo - attendances, not attenadances 
    var lowest = attenadances 
    .Select((value, index) => new { 
     attendance = value, 
     name = Names[index], }) 
    .Aggregate((s, a) => s.attendance < a.attendance ? s : a); 

    //DONE: { 1} should be {1} 
    //DONE: can a woman be the top truant? - his/her 
    string message = string.Format(
    "the person with the lowest attendance is {0} and his/her attendance is {1}", 
     lowest.name, 
     lowest.attendance); 

    //DONE: leading space eliminated 
    MessageBox.Show(message, "lowest attendance"); 

如果你不想的LINQ implemantation,我建議使用for isntead做的while

int lowestattendance = 0; 
    string lowestname = null; 

    for (int i = 0; i < Attenadances.Count; ++i) 
    // change min: on the very 1st item; if next item is less than current min 
    if (i == 0 || attenadances[i] < lowestattendance) { 
     lowestattendance = attenadances[i]; 
     lowestname = Names[i]; 
    } 

    string message = string.Format(
    "the person with the lowest attendance is {0} and his/her attendance is {1}", 
    lowestname, 
    lowestattendance); 

    MessageBox.Show(message, "lowest attendance"); 
+0

真的很好的答案:D,雖然我認爲這可能是一個先進的考慮問題的性質和開發者的經驗(據我可以告訴從這個問題) –

+0

@Alfie Goodacre:我個人比較喜歡* Linq *因爲它的可讀性(這就是爲什麼我開始使用它:如果我必須找出最高的逃學者,我會這樣做)。然而,我同意* Linq *對於新手開發者來說很難理解*,所以我提供了很好的''for'循環實現。 –

0

根據您發佈的代碼,你當你格式化你的消息FormatException。原因是您的佔位符{ 1}不允許前導空格。

所以更換您的格式代碼行

string message = string.Format(
    "the person with the lowest attendance is {0}" + 
    "and his attendance is {1}", // change here from { 1} to {1} 
    lowestname, lowestattendance); 

如果您還有其他問題,請在你的問題更具體。

0

while會工作作爲for循環好得多,像這樣

for (int i = 0; i < attenadances.Count; i++) 
    { 
     if (attenadances[i] < lowestattendance) 
     { 
      lowestattendance = attenadances[i]; 
      lowestname = Names[i]; 
     } 

    } 

通知我怎麼也去掉了分號?

while (index < attenadances.Count) ;變成for (int i = 0; i < attenadances.Count; i++)

這是因爲多餘的分號算作你的循環結束,所以電腦是看到

WHILE index IS LESS THAN attendances.Count DO NOTHING。因此,它永遠不會做任何事情!

相關問題