我想按照特定條件對自定義列表進行排序。列表中的每個項目都包含一個名爲「狀態」的屬性,它是一個枚舉,如下所示。列表自定義排序
Empty = 0, Normal = 1, Aged = 2, Dead = 3
上面指定的值不能更改。當我對我的狀態屬性進行排序時,我希望命令可以像正常,過期,空&死。我不知道如何去做這件事?
下面是我用於不同排序問題的類的示例。不知道我將如何'轉換'這個類來解決我上面的問題?使用在該比較
public static class StatusGoodExtensions
{
public static int OrderIndex(this StatusGood statusIn)
{
switch (statusIn)
{
case StatusGood.Normal: return 0;
case StatusGood.Aged: return 1;
case StatusGood.Empty: return 2;
case StatusGood.Dead: return 3;
}
throw new NotImplementedException(statusIn.ToString());
}
}
,像這樣::
public class SortOrders : IComparer<OrderBlocks.Order>
{
private bool _sortDescending;
public SortOrders(bool sortDescending)
{
this._sortDescending = sortDescending;
}
public SortOrders()
: this(false) // sort ascending by default
{
}
public int Compare(OrderBlocks.Order x, OrderBlocks.Order y)
{
if (this._sortDescending)
{
return y.StatusGood.CompareTo(x.StatusGood);
}
else
{
return x.StatusGood.CompareTo(y.StatusGood);
}
}
}
您可以使用LINQ來實現此功能。 –
最容易(但不一定是最有效的)方法很可能使用數組中枚舉值的「索引」:即以'new [] {Normal,Aged,Empty,Dead}'開頭。 OrderBy超過IEnumerable的超級簡單。 – user2864740