C# 基于结构数组c中的值进行排序#
我有一个结构数组,其中有一个名为total的数据项。我想根据整型数据项“total”对该数组进行排序C# 基于结构数组c中的值进行排序#,c#,arrays,C#,Arrays,我有一个结构数组,其中有一个名为total的数据项。我想根据整型数据项“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; o
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!
或
如果您计划对这些已排序的项目进行多次迭代,它将创建一个新的
疾病引用数组。如果您想对原始数组进行排序,数组。排序更合适/更有效:
Array.Sort(opDisease, (d1, d2) => d1.total.CompareTo(d2.total));
如果要按降序排序,只需反转条件,因此:
Array.Sort(opDisease, (d1, d2) => d2.total.CompareTo(d1.total));
.... 到目前为止您尝试了什么?谢谢,我如何访问变量SortedDisease?您是什么意思sortedDiseases
是一个新数组(在第二种情况下),因此您可以使用与opDisease
相同的方法,如sortedDiseases[1]。总计=10
。
Array.Sort(opDisease, (d1, d2) => d1.total.CompareTo(d2.total));
Array.Sort(opDisease, (d1, d2) => d2.total.CompareTo(d1.total));