[英]Sort based on a value in struct array c#
我有一个结构体数组,其中有一个数据项称为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);
要么
var sortedDiseases = opDisease.OrderBy(d=>d.total).ToArray();
如果您打算多次遍历这些已排序的项目,则会创建一系列新的Disease
参考。
如果要对原始数组进行排序,则Array.Sort
更合适/更有效:
Array.Sort(opDisease, (d1, d2) => d1.total.CompareTo(d2.total));
如果要对降序进行排序,则只需反转条件,所以:
Array.Sort(opDisease, (d1, d2) => d2.total.CompareTo(d1.total));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.