按字典的值属性对外键列表进行排序

I have an Dictionary<int, Person> with data of persons (read from Microsoft SQL Server). Key is the ID of the Person.

在一个函数中,我得到了带有一堆人的ID的列表。现在,我可以遍历此列表并打印出此人的子集。

foreach(int ID in PersonsList)
{
  Console.write(PersonsDictionary[ID].FullName);
} 

现在的问题是,字典或列表是否以任何方式排序,但我希望这些人按字母顺序排序。那么,如何按字典值的全名-属性对ID列表进行排序?

评论
  • bipsam
    bipsam 回复

    您可能想要这样的东西:

    IEnumerable<string> sortedNames = 
        PersonsList
            .Select(id => PersonsDictionary[id].FullName) // Select the name for each entry
            .OrderBy(n => n, StringComparer.OrdinalIgnoreCase); // Order the names (case insenstive)
    
    foreach(string name in sortedNames) // Materialize the ordered names
    {
        Console.Write(name); // print
    }
    

    You might need to add using System.Linq; at the top of your .cs file for this to work, since it uses LINQ extension methods:

    Note that, like your original code, this will throw a KeyNotFoundException if PersonsList contains a key that doesn't exist in PersonsDictionary.