简体   繁体   English

根据结构数组C#中的值排序

[英]Sort based on a value in struct array c#

I have an array of a struct which have a data item called total. 我有一个结构体数组,其中有一个数据项称为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. 如果您打算多次遍历这些已排序的项目,则会创建一系列新的Disease参考。

If you want to sort the original array, Array.Sort is more appropriate/efficient: 如果要对原始数组进行排序,则Array.Sort更合适/更有效:

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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