我有:
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'的定义。
我在这里做错了什么?
答案 0 :(得分:1)
您的声明所做的是返回IEnumerable(System.Linq.IOrderedEnumerable<System.Collections.Generic.KeyValuePair<int,int>>
)。
IEnumerable没有名为Key或Value的属性。它只允许您浏览内容。
您只是按其值排序字典的内容。
试试这个:
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();
答案 1 :(得分:0)
您可以使用其他形式的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();