【问题标题】:Cannot convert keys or values of a dictionary to an array in C#无法将字典的键或值转换为 C# 中的数组
【发布时间】:2015-05-10 09:02:11
【问题描述】:

我有: 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”的定义。

我在这里做错了什么?

【问题讨论】:

  • This 可以帮到你。
  • @Eminem Enumerable.ToDictionary 在这里没有帮助,因为他需要对其进行排序。

标签: c# arrays dictionary copy


【解决方案1】:

您的语句所做的是返回一个 IEnumerable (System.Linq.IOrderedEnumerable&lt;System.Collections.Generic.KeyValuePair&lt;int,int&gt;&gt;)。

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();

【讨论】:

    【解决方案2】:

    您可以使用其他形式的 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();
    

    【讨论】:

    • 将排序后的列表转换回字典时,顺序不会丢失吗?
    • @GaneshR。不,这不是您从OrderByDescending返回的子集创建字典时@
    • 字典中的顺序是不确定的。它适用于我创建但不能保证的测试。 stackoverflow.com/questions/4007782/…
    • @GaneshR。我知道,在另一个 .NET 实现中可能会有所不同,但微软一直以这种方式实现字典。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多