I have a List of type Test which has 4 properties and the List needs to be sorted with some specific conditions. Below are the properties of class Test and also sample data.
class Test
{
int order;
string value;
string dept;
//..... and some others
}
Sample json:
[
{
"order":3,
"value":"ABC",
"dept":"A"
},
{
"order":2,
"value":"XYZ",
"dept":"A"
},
{
"order":1,
"value":"ABC2",
"dept":"P"
},
{
"order":4,
"value":"XYZ2",
"dept":"P"
},
{
"order":6,
"value":"ABC3",
"dept":"Z"
},
{
"order":5,
"value":"XYZ3",
"dept":"Z"
},
]
The above json data is loaded to one List<Test>.
My requirement is to sort the above list like first the items with dept=P, then dept=A and then dept=Z and the second sort criteria is order.
I tried with OrderBy(x=>x.dept).ThenBy(x=>x.order) but the output is not what is expected.
Is there any way to specify the dept which should appear first in the list.
As a workaround I split the List into multiple lists and then merge them after sorting, but this is not the best solution I guess.
Do we have any other better and optimized solution for this?