简体   繁体   中英

Sort based on a value in struct array c#

I have an array of a struct which have a data item called total. I want to sort this array based on integer dataitem 'total'.

 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!
var sortedDiseases = opDisease.OrderBy(d=>d.total);

or

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

if you're planning to iterate over those sorted items more than once - it'll create a new array of Disease references.

If you want to sort the original array, Array.Sort is more appropriate/efficient:

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

If you want to sort descending you just have to reverse the condition, so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM