簡體   English   中英

根據結構數組C#中的值排序

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM