Sorting a Dictionary in place with respect to keys

前端 未结 7 1260
广开言路
广开言路 2020-11-29 04:49

I have a dictionary in C# like

Dictionary

and I want to sort that dictionary in place with respect to keys (a f

7条回答
  •  星月不相逢
    2020-11-29 05:21

    Due to this answers high search placing I thought the LINQ OrderBy solution is worth showing:

    class Person
    {
        public Person(string firstname, string lastname)
        {
            FirstName = firstname;
            LastName = lastname;
        }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    
    static void Main(string[] args)
    {
        Dictionary People = new Dictionary();
    
        People.Add(new Person("John", "Doe"), 1);
        People.Add(new Person("Mary", "Poe"), 2);
        People.Add(new Person("Richard", "Roe"), 3);
        People.Add(new Person("Anne", "Roe"), 4);
        People.Add(new Person("Mark", "Moe"), 5);
        People.Add(new Person("Larry", "Loe"), 6);
        People.Add(new Person("Jane", "Doe"), 7);
    
        foreach (KeyValuePair person in People.OrderBy(i => i.Key.LastName))
        {
            Debug.WriteLine(person.Key.LastName + ", " + person.Key.FirstName + " - Id: " + person.Value.ToString());
        }
    }
    

    Output:

    Doe, John - Id: 1
    Doe, Jane - Id: 7
    Loe, Larry - Id: 6
    Moe, Mark - Id: 5
    Poe, Mary - Id: 2
    Roe, Richard - Id: 3
    Roe, Anne - Id: 4
    

    In this example it would make sense to also use ThenBy for first names:

    foreach (KeyValuePair person in People.OrderBy(i => i.Key.LastName).ThenBy(i => i.Key.FirstName))
    

    Then the output is:

    Doe, Jane - Id: 7
    Doe, John - Id: 1
    Loe, Larry - Id: 6
    Moe, Mark - Id: 5
    Poe, Mary - Id: 2
    Roe, Anne - Id: 4
    Roe, Richard - Id: 3
    

    LINQ also has the OrderByDescending and ThenByDescending for those that need it.

提交回复
热议问题