C# 按字典的value属性对外键列表进行排序

C# 按字典的value属性对外键列表进行排序,c#,list,dictionary,C#,List,Dictionary,我有一本字典,上面有从Microsoft SQL Server读取的人员数据。Key是这个人的ID 在一个函数中,我得到一个列表,其中包含一组人员ID。现在我可以循环浏览这个列表并打印出这些人的子集 PersonList中的ForEacht ID { Console.writePersonsDictionary[ID]。全名; } 现在的问题是,无论字典还是列表是按任何方式排序的,但我希望这些人按字母顺序排列。那么,如何根据字典值的FullName属性对ID列表进行排序呢?您可能希望这样: I

我有一本字典,上面有从Microsoft SQL Server读取的人员数据。Key是这个人的ID

在一个函数中,我得到一个列表,其中包含一组人员ID。现在我可以循环浏览这个列表并打印出这些人的子集

PersonList中的ForEacht ID { Console.writePersonsDictionary[ID]。全名; }
现在的问题是,无论字典还是列表是按任何方式排序的,但我希望这些人按字母顺序排列。那么,如何根据字典值的FullName属性对ID列表进行排序呢?

您可能希望这样:

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
}
您可能需要使用System.Linq;在.cs文件的顶部,由于它使用LINQ扩展名方法,因此可以执行此操作:

请注意,与原始代码一样,如果PersonList包含PersonDictionary中不存在的键,则会引发KeyNotFoundException


你可能想要这样的东西:

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
}
您可能需要使用System.Linq;在.cs文件的顶部,由于它使用LINQ扩展名方法,因此可以执行此操作:

请注意,与原始代码一样,如果PersonList包含PersonDictionary中不存在的键,则会引发KeyNotFoundException


非常感谢你!成功了!我做了一些修改,以获得ID的排序列表,而不是名称,但这给了我必要的提示。SelectID=>PersonsDictionary[ID].ID.OrderByn=>PersonsDictionary[n].Fullname,StringComparer.OrdinalIgnoreCase;我知道KeyNotFoundException,但这没有问题,因为我是通过foreach和字典中的一些if得到这个列表的。非常感谢!成功了!我做了一些修改,以获得ID的排序列表,而不是名称,但这给了我必要的提示。SelectID=>PersonsDictionary[ID].ID.OrderByn=>PersonsDictionary[n].Fullname,StringComparer.OrdinalIgnoreCase;我知道KeyNotFoundException,但这没有问题,因为我是通过foreach和字典中的if获取列表的。