How to sort (1,11,12,2,All,Others) to (All,1,2,11,12,Others)?
1
10
11
12
2
3
4
All
Others
How to make the drop down look like:
All
1
2
3
4
10
11
12
Others
OR
In SQL I try to ORDER BY CAST(priorityNum AS UNSIGNED INTEGER)
after that I add All
and Other
into my datatable result. But how to set 开发者_如何学Pythonthe All
and Others
to be always first and last?
As long as your collection is an IEnumerable
, you can invoke OrderBy
with a custom comparer method.
Your comparer would look like this:
class myStringComparer: IComparer<string> {
public int Compare(string a, string b) {
if (a == b) return 0;
if (a == "All" || b == "Others") return -1;
if (a == "Others" || b == "All") return 1;
return int.Parse(a) - int.Parse(b);
}
}
This, as is, will just throw an exception if unexpected data is found (anything else than "All", "Others", or a number). You may want to add additional logic before attempting the integer parsing.
Now, you can call .OrderBy(new myStringComparer())
on your list/collection. Note that OrderBy
will only be available for IEnumerable
objects (this includes anything you can put on a foreach
loop, such as arrays, lists, etc).
Is there a reason why you have it stored as a varchar? It should really be an int and this will solve your problem - and be the correct type for your storage
Ideally you could use something like List(T).Sort http://msdn.microsoft.com/en-us/library/w56d4y5z.aspx#Y851
When you make the comparer, check to see if the value is an int, if it is, compare it as normal, if not, you know its one of your All/Other cases. You then return a value based on which string you are working on.
That said, if you can just put the ints in the database instead of putting in All and Others and then put them in at runtime it'd make sorting a whole lot easier.
You need some special comparison method. It should check if the both strings are numbers, then compare using their numeric value. If the first value if All or Others and the second is number, the first value is smaller. If the first is All and the second is Others, the first is smaller.
You should either handle (sort) the numbers seperately from the texts and reconstruct the list afterwards. Or store all items which are not sortable in a seperate dictionary, f.e.:
All -> 0
Other -> int.MaxVallue
Than you walk the unsorted list, seperate the non-number items (via the dictionary or Int.TryParse) from the numbers, sort the numbers in a list and insert the text items from the dictionary afterwards.
Sounds complicated but prepares for changes of those non-number items.
First hand, sort by length and then value, that would solve your problem with 11 coming before 2.
For your two special words, you will need some magic.
I solved it by Using CAST at SQL Comment and Add the "All" and "Others" into my datatable in programmatically way.
精彩评论