You could create another list in the correct order, by something like:
// Given that 'Person' for the sake of this example is:
public class Person
{
public string FirstName;
public string LastName;
}
// And you have a dictionary sorted by Person.FirstName:
var dict = new SortedDictionary<string, Person>();
// ...initialise dict...
// Make list reference a List<Person> ordered by the person's LastName
var list = (from entry in dict
orderby entry.Value.LastName
select entry.Value).ToList();
// Use list to populate the listbox
This has the advantage of leaving the original collection unmodified (if that's important to you).
The overhead of keeping references to the objects in two different collections is not very high, because it's only one reference per object (plus some fixed overhead for the List<>
implementation itself).
But remember that the objects will be kept alive as long as either of the collections are alive (unless you explicitly clear the collections).
Compilable sample:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Demo
{
public static class Program
{
private static void Main()
{
dict = new SortedDictionary<string, Person>();
addPerson("iain", "banks");
addPerson("peter", "hamilton");
addPerson("douglas", "adams");
addPerson("arthur", "clark");
addPerson("isaac", "asimov");
Console.WriteLine("--------------");
foreach (var person in dict)
Console.WriteLine(person.Value);
var list = (from entry in dict
orderby entry.Value.LastName
select entry.Value).ToList();
Console.WriteLine("--------------");
foreach (var person in list)
Console.WriteLine(person);
}
private static void addPerson(string firstname, string lastname)
{
dict.Add(firstname, new Person{FirstName = firstname, LastName = lastname});
}
private static SortedDictionary<string, Person> dict;
}
public class Person
{
public string FirstName;
public string LastName;
public override string ToString(){return FirstName + " " + LastName;}
}
}