Reputation: 22054
I need to sort some codes, but in a strange manner
I need to sort in a non-normal order, I need to sort the 40s first, then 50s, 90s, 70s, 80s, 60s, 20s, 30s, 10s, 00s.
What's the best way to go about this?
It's in C#.net 3.5
Upvotes: 1
Views: 114
Reputation: 28762
You can usually provide a custom method to do the sorting (either to a sort method or a sorted collection class that holds these values.
Or are you asking what the algorithm inside that method should be?
For the algorithm, you can use the following methods:
int getFirstOrder(int v) {
if (50 <= v && v <= 59) {
return 1;
} else if (90 <= v && v <= 99) {
return 2;
}
// and so on
}
int Compare (int v1, int v2)
{
int o1 = getFirstOrder(v1);
int o2 = getFirstOrder(v2);
if (o1 < o2 || (o1 == o2 && v1 < v2)) {
return -1;
} else if (o1 > o2 || (o1 == o2 && v1 > v2)) {
return 1;
} else {
return 0;
}
}
I'm sure there is a more efficient way (especially for getFirstOrder()
, but this should put you in the right direction
Upvotes: 3
Reputation: 22054
I ended up using this
private class CodeComparer : IComparer<Code>
{
public int Compare(Code x, Code y)
{
var order = "4597862310";
var bodyStyleX = x.Substring(6, 2);
var bodyStyleY = y.Substring(6, 2);
// Same body style group
if (bodyStyleX[0].Equals(bodyStyleY[0]))
return string.Compare(bodyStyleX, bodyStyleY, true);
var indexX = order.IndexOf(bodyStyleX[0]);
var indexY = order.IndexOf(bodyStyleY[0]);
return indexX < indexY ? -1 : 1;
}
}
Upvotes: 0
Reputation: 203821
Most sorting methods can take an IComparer
object, so if you can write a method that takes two items and can say which comes first, you can sort using that comparer method.
Upvotes: 3