简体   繁体   English

如何在C#中基于自定义顺序对基于属性的对象数组进行排序?

[英]How to sort an array of objects based on a property in custom order in C#?

I have the following code 我有以下代码

CustomerModel[] customerModel ;

customerModel = GetCustomerModel(customerReport);

Now this CustomerModel class has a string property called DealType with possible values of "CostOnly","Edlp","NonPromoted","Periodic" . 现在,此CustomerModel类具有一个名为DealType的字符串属性,其可能值为"CostOnly","Edlp","NonPromoted","Periodic"

All I want is to sort the customerModel array order by DealType property in the follwing order. 我想要的只是按照以下顺序对DealerModel数组顺序按DealType属性进行排序。

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

What is the most optimal approach to solve this? 解决此问题的最佳方法是什么?

Thanks in Advance. 提前致谢。

You can sort by the index of an item in list of sequential custom order like this: 您可以按顺序自定义订单列表中的项目索引进行排序,如下所示:

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

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

This sorts each element by its order in the sortOrderList 这将按sortOrderList顺序对每个元素进行排序

Another option would be to use Array.Sort() to do in-Place sorting: 另一个选择是使用Array.Sort()进行就地排序:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM