masterial
masterial

Reputation: 2216

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; }
}

Upvotes: 0

Views: 616

Answers (2)

kurakura88
kurakura88

Reputation: 2305

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...!

Upvotes: 1

Lee Campbell
Lee Campbell

Reputation: 10783

You are using a non generic (IMO legacy) data type. So you will need to poke it a bit to get what you want.

people.Values.OfType<Person>().OrderBy(p => p.LastName);

First you want to sort the values, but that isn't generic, so use OfType. Now you can play with the standard Linq operators like OrderBy

Upvotes: 0

Related Questions