2016-07-29 92 views
0

我有以下代碼如何基於C#中的自定義順序中的屬性對對象數組進行排序?

CustomerModel[] customerModel ; 

customerModel = GetCustomerModel(customerReport); 

現在這個CustomerModel類有一個名爲DealType"CostOnly","Edlp","NonPromoted","Periodic"可能值的字符串屬性。

我只想按照以下順序通過DealType屬性對customerModel數組排序進行排序。

"NonPromoted", 
"Edlp", 
"Periodic", 
"CostOnly" 

解決此問題的最佳方法是什麼?

在此先感謝。

+0

可能的複製 - http://stackoverflow.com/questions/8975698/implementing-custom-icomparer-with-string – ChrisF

回答

4

您可以通過一個項目的順序定製訂單列表中的索引這樣的排序:

List<string> sortOrderList = new List<string>() 
{ 
    "NonPromoted", 
    "Edlp", 
    "Periodic", 
    "CostOnly" 
}; 

customerModel = customerModel.OrderBy(x=> sortOrderList.IndexOf(x.DealType)).ToArray(); 

這通過其在sortOrderList

順序排序的每個元素的另一種選擇是使用數組的.sort()做就地排序:

Array.Sort(customerModel, (x, y) => sortOrderList.IndexOf(x.DealType) - 
            sortOrderList.IndexOf(y.DealType)); 
+0

它爲我工作。非常感謝。 :) – user3407500

相關問題