The other day I had to sort a list by a datetime field. Given that this was an ASP.NET project, the easiest way that comes to mind to do that is to just sort the data on the server side, using LINQ, by writing a Comparer Class, or some other custom sort routine.
Unfortunately for me those options were not available to me because:
- Collection I needed to sort was coming from an “black box” API, and one which I had no access to. Furthermore, even though they provided a Sort method on collections, it wasn’t working.
- LINQ was out of the question because the application could only run on the .NET Framework 2.0.
- Writing a custom sorter would have blow the budget out of the water. I needed a quick and easy solution to this problem.
What is jQuery and TinySort?
So I was now on a mission to sort the list on the client-side instead, using jQuery sort and the TinySort plug-in. After a quick cursory review of TinySort, I realized this was just the solution I was looking for.
TinySort will sort any node type by it’s text- or attribute value, or by that of one of it’s children. The syntax to sort is quite simple. The following snippet assumes that you are trying to sort an unordered list with an id of “people”:
TinySort supports a ton of other options including sort direction etc, however, the one thing it did not support is sort by other data types. As I mentioned above TinySort is only able to sort by text.
This was a big problem for me, because what I was trying to do was to sort by date and time. I was trying to sort a list of sessions, where they had a start and end time.
After giving it a little more thought I realized that I could convert any datatime field value to “ticks”. The Ticks property on a datetime data type gets the number of ticks that represent the date and time of this instance (ref: https://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx).
How to sort unordered list using jQuery Sort and TinySort?
So with that in mind, I created a span within which I placed the ticks representation of the datetime field I need to sort by as shown on line 11 below:
[code lang=”html”]&lt;asp:Repeater ID=”repSessions” runat=”server”&gt;
&lt;!– Ticks below are used for sorting only –&gt;
Now that I have the field that supports sorting (i.e: a simple number representation of the datetime) I sort it as so:
The first line above tells TinySorts to sort the list by the contents of the SPAN tag within the unordered list’s list items, in ascending order.
The second line simply hides all the SPAN elements which contain the ticks and that make no sense of showing to the user.
So if you run into a similar situation, you might want to go this route. It not only works really well, but it also saves the server-side over head of custom sorting the collection yourself and will save you quite a bit of time that if would take to build a custom sorter.