无法将字典的键或值转换为 C# 中的数组

Cannot convert keys or values of a dictionary to an array in C#

我有: Dictionary<int, int> Color_Count = new Dictionary<int, int>();

还有:var sortedDict = from entry in Color_Count orderby entry.Value descending select entry;

但我不知道如何修复这个编译器错误。当我试图将键从这本字典复制到整数时,像这样:

int[] Colors_massive = sortedDict.Keys.ToArray();

它导致错误 CS1061:

'System.Linq.IOrderedEnumerable<System.Collections.Generic.KeyValuePair<int,int>>' does not contain a definition for 'Keys' and no extension method 'Keys' accepting a first argument of type 'System.Linq.IOrderedEnumerable<System.Collections.Generic.KeyValuePair<int,int>>' could be found (are you missing a using directive or an assembly reference?)   

如果我尝试复制,使用其他方法:

int[] Colors_massive = new int[sortedDict.Keys.Count];
        sortedDict.Keys.CopyTo(Colors_massive, 0);

它也会导致同样的错误,但现在错误打印了两次。如果我将代码中的单词 'Keys' 替换为单词 'Values',它也会打印相同的错误,但现在编译器无法找到 'Values'.

的定义

我做错了什么?

你的语句所做的是 return 一个 IEnumerable (System.Linq.IOrderedEnumerable<System.Collections.Generic.KeyValuePair<int,int>>)。

IEnumerable 没有 属性 称为键或值。它只允许您对内容进行交互。

您只是按值对字典的内容进行排序。

试试这个:

    Dictionary<int, int> Color_Count = new Dictionary<int, int>();
    List<KeyValuePair<int, int>> sortedDict = Color_Count.OrderByDescending(entry => entry.Value).ToList();
    int[] Colors_massive = sortedDict.Select(x => x.Key).ToArray();
    List<int> orderedValues = sortedDict.Select(x => x.Value).ToList();

您可以使用其他形式的 LINQ 来简化事情

var sortedDict = Color_Count.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

sortedDict 仍然是字典,您可以访问它的 Keys 集合

如果你只是想创建一个键数组,那就更简单了

int[] sorted = Color_Count.OrderByDescending(x => x.Value).Select(x => x.Key).ToArray();