2013-06-22 123 views
-7

我有一個XML文件:排序列表numericallyC#

<highscore> 
    <score> 
    <naam>rake</naam> 
    <punten>100</punten> 
    </score> 
    <score> 
    <naam>john</naam> 
    <punten>200</punten> 
</score> 
</highscore> 

和代碼把值列表和顯示:

public Highscores() 
    { 
     InitializeComponent(); 

     XmlNode node = this.xmlbeheer.Open("Highscores/Highscores.xml"); 
     List<Score> scores = new List<Score>(); 


     foreach (XmlNode score in node.ChildNodes) 
     { 

      if (score.Name == "score") 
      { 
       Score s = new Score(); 
       foreach (XmlNode child in score.ChildNodes) 
       { 
        if (child.Name == "naam") 
        { 
         s.Naam = child.InnerText; 
        } 
        if (child.Name == "punten") 
        { 
         s.Punten = child.InnerText; 
        }      
       } 
       scores.Add(s); 
      } 
     } 

     foreach (Score s in scores) 
     { 
      if (n < 5) 
      { 
       Label naam = new Label(); 
       naam.Top = 10 + 23 * n; 
       naam.Text = (n + 1) + ". " + s.Naam; 
       naam.Left = 0; 
       pnlScores.Controls.Add(naam); 

       Label punten = new Label(); 
       punten.Top = 10 + 23 * n; 
       punten.Text = s.Punten; 
       punten.Left = 140; 
       pnlScores.Controls.Add(punten); 
      } 
      n++; 
     } 
    } 

但我的問題是如何排序的「 punten「從數字上形成高到低? 我在網上看到了很多東西,但我不明白他們:(

我真的很感激的答案!

謝謝!

+0

我昨天回答了幾乎與此相同的東西.http://stackoverflow.com/questions/17231446/select-top-5-records-from-xml-with-c-sharp/17231588#17231588 – James

+0

你需要採取幾個步驟回,並試圖將其應用到XML文件 –

+0

Youly代碼只添加一個項目到列表之前學習的C#和泛型的基礎知識! –

回答

0

可以就地排序scores,如果你想使用List.Sort(Comparison<T>)

scores.Sort((a, b) => int.Parse(a.Punten).CompareTo(int.Parse(b.Punten))); 

注意,因爲Punten似乎是一個字符串,你需要將其轉換爲int正確比較。

如果你改變你的代碼,使Punten一個int,分類代碼將簡化爲:

scores.Sort((a, b) => a.Punten.CompareTo(b.Punten)); 

這裏發生的事情是,我們提供一個比較函數與排序將會對項目的比較確定所需的訂單。

(a, b)在上面的代碼中指定了要比較的列表的元素類型的兩個參數。我們只需要比較他們的Punten屬性。

0

由於punten是一個字符串,則必須將其轉換爲一個int,然後你可以使用OrderByDescending並做到這一點:

var sortedByPunten = scores.OrderByDescending(s => Int32.Parse(s.punten)); 
+0

該行's.Punten =孩子。InnerText;'表示它是一個字符串。 –

+0

@MikePrecup - 不錯的地方。他必須將其改爲int或執行演員。 –

0

您應該使用OrderByDescending LINQ方法和該方法的字符串轉換爲整數(例如使用Convert.ToInt32):

所有的
var scores = scores.OrderByDescending(x => Convert.ToInt32(x.Punten)); 
0

首先,你只需要添加一個項目到您的列表

Score s = new Score(); 
       foreach (XmlNode child in score.ChildNodes) 
       { 
        if (child.Name == "naam") 
        { 
         s.Naam = child.InnerText; 
        } 
        if (child.Name == "punten") 
        { 
         s.Punten = child.InnerText; 
        } 
       scores.Add(s); // <-- move here and delete the one under this 
       } 
       scores.Add(s); // <-- see adding s to the List s outside the loop 

固定,要像谷歌或這裏有C#排序列表中的一些很好的答案後。我真的覺得你需要花一分鐘多學習一點C#的基礎知識,現在你已經是這麼寫的,你必須硬編碼XML的每個節點都在你的C#,甚至讀取XML文件什麼意義呢?

+0

我猜OP張貼了他的文件的一個樣本,而不是整個事情。但謝謝你張貼答案:) – Tim

+0

我明白了,但可能再次也許不 - OP是問如何排序一個通用的列表,這導致我相信OP是非常新鮮的編程 –