nebulus nebulus - 10 months ago 62
C# Question

How to sort a hashtable of class values by their property in c#?

I have a Hashtable in C# like.

Hashtable people = new Hashtable();
people.Add(0, new Person("Jimmi", "Hendrix"));
people.Add(1, new Person("Bob", "Dylan"));
people.Add(2, new Person("Jim", "Morrison"));

How would I sort this hash by the people last name with Linq?

class Person
public Person(string firstName, string lastName): this(firstName, lastName, DateTime.Now)

public Person(string firstName, string lastName, DateTime birthDate)
FirstName = firstName;
LastName = lastName;
DateOfBirth = birthDate;

public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }

Answer Source
var result = people.Cast<DictionaryEntry>().OrderBy(kvp => ((Person)kvp.Value).LastName);

the result becomes OrderedEnumerable though, because putting back to Hashtable will forget the order.\

EDIT: If you are looking for a way to enumerate the result and pull out the id's along with the Person information, this is how you do it:

// this is the original answer
var result = people.Cast<DictionaryEntry>().OrderBy(kvp => ((Person)kvp.Value).LastName);

// now convert it to an array
var listToIterate = result.ToArray();
foreach(var item in listToIterate)
    var id = item.Key;
    var person = (Person)item.Value;

Hope this helps...!