Home > database >  Custom Sort a ListBox in C# Visual Studio
Custom Sort a ListBox in C# Visual Studio

Time:01-31

I'll start by giving an example cause it will be easier.

Lets say I have a ListBox that's named "lbDestinations" and I have a class for that listbox called Destination.

Destination.cs

public class Destination
{
    public string Name { get; set; }
    public int Distance { get; set; }
    public int Price { get; set; }

    public Destination(string name, int distance, int price)
    {
        Name = name;
        Distance = distance;
        Price = price;
    }

    public override string ToString()
    {
        return string.Format("{0} {1} km {2} $", Name, Distance, Price);
    }
}

Now I want to add destinations with a name, the distance to that location and the price for that trip. Lets have a couple destinations added for examples and stuff..

London 100 km  200 $
Berlin 400 km  800 $
Paris 200 km  400 $
Madrid 150 km  300 $

Now if I have all those in that order in the ListBox and I do lbDestinations.Sorted it will Sort them alphabetically, but I don't want that..

I want to sort them by the distance or the price.. The output has to be "Name Distance Price"

I tried a couple things but none of them worked

CodePudding user response:

Instead of adding items to the listbox one by one, you can assign a collection to the DataSource of the listbox. This enables you to apply a custom sort to the collection.

E.g.

var destinations = new List<Destination>();
destinations.Add(new Desination { Name = "London", Distance = 100, Price = 200 });
...
destinations.Sort( (a, b) => a.Price.CompareTo(b.Price) );
lbDestinations.DataSource = null; // Ensures the listbox refreshes.
lbDestinations.DataSource = destinations;

You can also use LINQ to sort by more than one column:

var destinations = source
    .OrderBy(d => d.Price)
    .ThenBy(d => d.Name)
    .ToList();
  • Related