LINQ顺序不能在字典键上工作

本文关键字:工作 字典 顺序 不能 LINQ | 更新日期: 2023-09-27 17:49:22

对我来说似乎没问题,但我的列表仍然没有按我的键排序。

    var tagNamesAndRoutes = new Dictionary<string, string>();
    foreach (string name in tagNames)
    {
        tagNamesAndRoutes.Add(name, routeConstant);
    }

字典值示例:

Key       Value
"NUnit"     "/Category"
"WCF"       "/Category"
"ReSharper" "/Category"

等等

我试着用典型的LINQ:

来排序
tagNamesAndRoutes.OrderBy(c => c.Key);

但是没有排序

LINQ顺序不能在字典键上工作

OrderBy实际上返回给您有序的集合。试试这个:

var orderedTagNamesAndRoutes = tagNamesAndRoutes.OrderBy(c => c.Key);

则使用orderedTagNamesAndRoutes

如果你想让你的字典自己排序,你可以使用SortedDictionary。试一试:

var tagNamesAndRoutes = new SortedDictionary<string, string>();

在这种情况下不需要调用OrderBy。字典总是按键排序。

OrderBy返回一个IOrderedEnumerable,您可以按排序顺序进行迭代,而不会修改实际的字典。

所以你需要输入

var sorted = tagNamesAndRoutes.OrderBy(c => c.Key);
foreach (string name in sorted) {
    ...
}

Dictionary类型本身没有键的顺序概念。你可以使用SortedDictionary,如果你总是想排序键。

https://msdn.microsoft.com/en-us/library/vstudio/bb534966%28v=vs.100%29.aspx