I have a problem which I cant seem to find answer to 开发者_Go百科through searches (either that or I am searching for the completely wrong thing!). I have a list of items called "Top 10" in a sortedlist item that is populated from my DB (SortedList where int is position and string is item). I want to be able to move items up & down the list order at the click of a button and then save the new order back to the DB. I am OK with the DB part it is just the re-ordering I am really struggling with - is a sortedlist the correct collection for this?
Many thanks for any advice offered.
A SortedList is for maintaining order within your SortedList as you add or remove items from it.
You should create a custom list of your objects and then sort on property of that object.
So if your entry in your database was like this you could place it in an object, add it to a list and then sort it using Lambda on which ever criteria you like
public class LeaguePosition
{
public int Position { get; set; }
public string Team { get; set; }
}
List<LeaguePosition> League = new List<LeaguePosition>();
League.Add(new LeaguePosition() { Position = 2, Team = "Wolves" });
League.Add(new LeaguePosition() { Position = 3, Team = "Spurs" });
League.Add(new LeaguePosition() { Position = 1, Team = "Villa" });
League.Sort((teamA, teamB) => teamA.Position.CompareTo(teamB.Position));
You can also then use RemoveAt() and Insert() to move items about to custom positions within the list.
LeaguePosition teamToMove = League[1];
League.RemoveAt(1);
League.Insert(2, teamToMove);
No, a SortedList will keep things in sorted (alpha/numeric) order. You want a plain list that will let you pull things out and insert them at different positions.
A SortedList is going to force each item to keep track of its position within the list relative to the other items (your int position). This should be a responsiblity of the Collection, so you should use some sort of Collection that will allow you to move things up/down/around without having to manually correct each item.
I would say a SortedList is exactly what you want. When you get data back from the database you want to keep it in order based on the position field (what I can tell from your OP). I'm assuming you will have a class that contains the data you're getting back from the DB. To keep the data in the right order you will need to implement the IComparable interface in your custom class so that the SortedList knows what values to use to keep the list in order. This way as you add/remove items you will keep them in the right order.
You could use a generic List<> but then you have to write all the code to sort your items yourself, the SortedList already does this so why re-invent the wheel?
Take a look at this page for more info:
http://www.dotnetspider.com/resources/4679-Applying-custom-sort-SortedList.aspx
精彩评论