2014-05-08 62 views
-1

我有一個結構數組,其中有一個名爲total的數據項。我想根據整數數據項'total'對這個數組進行排序。根據結構數組c中的值排序#

struct Disease 
{ 

    public int male; 
    public int female; 
    public int total=0; 
    public string diseaseName; 

} 
Disease [] opDisease = new Disease [21]; 
opDisease[0].total= somevalue1; 
opDisease[1].total= somevalue2; 
      ... 
      ... 
      ... 
      ... 


I want to sort opDisease array based on the value of 'total'. 

thank you! 
+0

。 ... 你試過什麼了? –

回答

4

如果你想在原來的數組進行排序,Array.Sort更合適/高效:

Array.Sort(opDisease, (d1, d2) => d1.total.CompareTo(d2.total)); 

如果你想降序排序,你只需要扭轉的條件,所以:

Array.Sort(opDisease, (d1, d2) => d2.total.CompareTo(d1.total)); 
4
var sortedDiseases = opDisease.OrderBy(d=>d.total); 

var sortedDiseases = opDisease.OrderBy(d=>d.total).ToArray(); 

如果你打算遍歷這些排序的項不止一次 - 它會創建Disease引用新的數組。

+0

謝謝,我怎樣才能訪問變量sortedDiseases? – afom

+0

你是什麼意思? 'sortedDiseases'是一個新的數組(第二種情況),所以你可以像'opDisease'一樣使用它,比如'sortedDiseases [1] .total = 10'。 – Tarec

+0

非常感謝你! – afom