0

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".

All I want is to sort the customerModel array order by DealType property in the follwing order.

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

What is the most optimal approach to solve this?

Thanks in Advance.

user3407500
  • 35
  • 1
  • 6
  • Possible duplicate - http://stackoverflow.com/questions/8975698/implementing-custom-icomparer-with-string – ChrisF Jul 29 '16 at 11:16

1 Answers1

4

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

Another option would be to use Array.Sort() to do in-Place sorting:

Array.Sort(customerModel, (x, y) => sortOrderList.IndexOf(x.DealType) - 
                                    sortOrderList.IndexOf(y.DealType));
Zein Makki
  • 29,485
  • 6
  • 52
  • 63