views:

106

answers:

1

Hi

I have a list of data that users are able to control the sort order of.

It looks something like this

Apples     /\  \/
Oranges    /\  \/
pears      /\  \/
banana     /\  \/
Pineapples /\  \/
etc        /\  \/

the /\ and \/ are meant to be up and down arrows

When the user clicks up i want to retrieve the current sort order and take one away fro it (so it has a smaller value and will be higher in the sort order.

When the user clicks down I do the opposite

I guess I also need to establish if there is already something else in the list with the new value I want to assign and adjust that item's sort order in the opposite direction

Does this seem like a good way to achieve this?

Or is there a smarter way?

Anyone got any sample code. I am using .net 3.5 so linq is OK

The list is stored in an in memory cache - IList<mycustomobj>

any suggestions gratefully received

EDIT: The issues I am worried about are when there is no sort order initially - everything will be zero. And my suggested algorithm has an implicit assumption that the sort order will always be continuous. But what happens when a row is deleted? there will be a gap in the list of sort orders, so simply adding 1 and taking away 1 might not make any difference - how do I handle this scenario?

+1  A: 

That's a way to do it. In my application we either use drag-and-drop, or have one up arrow and one down arrow to move the selected element up/down.

If you have some property determining the sort order, when the user clicks the up arrow you just need to permutate the current element's sort position with the previous element's sort position, unless it's the first element (do nothing in that case). Use the reverse logic for the down arrow...

Edit:

If your items don't have a sort position yet, you could just go through your list and assign a sort position from 1 to n. In case of a deleted row, decrease the sort position of all following items by one.

Meta-Knight
Exactly. Swap the sort values of the two items being exchanged.
Nick Johnson