Here is the job schedule class:
public class JobSchedule
{
public string Customer { get; set; }
public string SchedulePriority { get; set; }
public override string ToString()
{
return string.Format("{0} :: {1}", Customer, SchedulePriority);
}
}
The priority class:
public class SchedulePriority
{
public SchedulePriority(string code, string description)
{
Code = code;
Description = description;
}
public string Code { get; private set; }
public string Description { get; private set; }
public override string ToString()
{
return string.Format("{0} :: {1}", Code, Description);
}
}
Below is a sample list data:
var list = new List<JobSchedule>{
new JobSchedule{
Customer = "jon",
SchedulePriority = new SchedulePriority("P","PM")
},
new JobSchedule{
Customer = "jane",
SchedulePriority = new SchedulePriority("O","Any")
},
new JobSchedule{
Customer = "bob",
SchedulePriority = new SchedulePriority("A","AM")
},
new JobSchedule{
Customer = "bonnie",
SchedulePriority = new SchedulePriority("F","First")
},
};
The requirement is to sort is this order:
“F”, “A”, “O”, “P”
If I were to sort it alphabetically as the following:
Console.WriteLine("Sort by Alphabetical Order and the result does NOT match the requirement");
foreach (var js in list.OrderBy(m => m.SchedulePriority.Code))
{
Console.WriteLine(js.ToString());
}
This is the result I get:
Sort by Alphabetical Order and the result does not meet the requirement
bob :: A :: AM
bonnie :: F :: First
jane :: O :: Any
jon :: P :: PM
So we create a custom comparer by implementing the ICompare interface:
public class SchedulePriorityOrderComparer : IComparer<SchedulePriority>
{
readonly Dictionary<string, int> _priorities = new Dictionary<string, int>() {
{"F", 1},
{"A", 2},
{"O", 3},
{"P", 4}
};
public int Compare(SchedulePriority x, SchedulePriority y)
{
if (string.IsNullOrWhiteSpace(x.Code) || string.IsNullOrWhiteSpace(y.Code)) return 0;
return _priorities[x.Code] - _priorities[y.Code];
}
}
Now I can sort it this as follows:
Console.WriteLine("Sort by Alphabetical Order and the result MATCH the requirement");
foreach (var js in list.OrderBy(m => m.SchedulePriority, new SchedulePriorityOrderComparer()))
{
Console.WriteLine(js.ToString());
}
And the result now looks like this:
Sort by custom order and the result MATCH the requirement
bonnie :: F :: First
bob :: A :: AM
jane :: O :: Any
jon :: P :: PM