2014-05-08 141 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