Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-ordering collection C#

I have a problem which I cant seem to find answer to 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.

like image 893
Adam Avatar asked Mar 30 '10 17:03

Adam


1 Answers

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);
like image 199
Nicholas Murray Avatar answered Oct 05 '22 23:10

Nicholas Murray