159753
159753

Reputation: 53

C# - sorting Dictionary

I have a Dictionary and I want to sort it by Person, could anyone write me how to do it? Yeah, I tried to find it in the internet, but without success :((

Class subject has 3 parametres - name (string), family_name (string), age (int).

And I want to sort it by for example family_name, if same then by age and finally by name (if also age is same) - could anyone write me the code how to do it?? Thanks a lot for your help ;-)

Upvotes: 0

Views: 1622

Answers (5)

Farzin Zaker
Farzin Zaker

Reputation: 3606

Define a Person and a Comparer class :

    public class Person
    {
        public string Name { get; set; }
        public string FamilyName { get; set; }
        public int Age { get; set; }
    }

    public class PersonComparer : IComparer<KeyValuePair<string, Person>>
    {
        public int Compare(KeyValuePair<string, Person> x, KeyValuePair<string, Person> y)
        {
            var result = x.Value.FamilyName.CompareTo(y.Value.FamilyName);
            if(result != 0)
                return result;

            return x.Value.Age.CompareTo(y.Value.Age);
        }
    }

and use these classes lie this :

 var myDictionary = new Dictionary<string, Person>();
 //fill your dictionary
 var list = myDictionary.ToList();
 list.Sort(new PersonComparer());

this is a simple and working solution.

Upvotes: 0

Ben Hoffstein
Ben Hoffstein

Reputation: 103345

You can use SortedList or SortedDictionary, both of which sort by the key.

Since the key is a class you created, you can pass an IEqualityComparer into the constructor to control how it gets sorted.

Upvotes: 0

StriplingWarrior
StriplingWarrior

Reputation: 156524

The Dictionary class can't be sorted due to the way it stores values, but you can easily get a sorted collection of the values that you have in your dictionary using LINQ.

var sorted = dictionary.Values.OrderBy(s => s.name)
                              .ThenBy(s => s.family_name)
                              .ThenBy(s => s.age);

Upvotes: 2

Mark Sowul
Mark Sowul

Reputation: 10600

There are SortedDictionary and SortedList you can use; you'd want to make an IComparer for Person as well. See this for a discussion of their differences: http://msdn.microsoft.com/en-us/library/5z658b67(VS.80).aspx

Upvotes: 5

Marek Kwiendacz
Marek Kwiendacz

Reputation: 9844

Dictionary is structure without order, so you cannot sort it - you can sort ordered structures like list

Upvotes: 0

Related Questions