【问题标题】:C#: "'System.Collections.Generic.Dictionary<object,object>.KeyCollection' does not contain a definition for 'ToList'" errorC#:“'System.Collections.Generic.Dictionary<object,object>.KeyCollection' 不包含 'ToList' 的定义”错误
【发布时间】:2021-11-29 23:59:01
【问题描述】:

我有以下代码试图在字典中获取值,但似乎无法正常工作。

using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;

namespace DemoTests
{
    class Program
    {
        static void Main(string[] args)
        {
            string jsonString = "{\"Name\":\"Bob Smith\",\"mainTitle\":\"Title1\",\"emailList\":[\"test.e@example.com\"],\"rowCount\":\"4\",\"emailSubject\":\"Test Email\",\"items\":{\"sheets\":[[{\"ID\": \"4564342\", \"start\": \"08:00\"}]]}}";
            JObject jsonObj = JObject.Parse(jsonString);
            Dictionary<dynamic, dynamic> results = jsonObj.ToObject<Dictionary<dynamic, dynamic>>();
  
            List<dynamic> subList = results["items"]["sheets"].ToObject<List<dynamic>>();
            foreach (dynamic tableEntries in subList) 
            {
                var entryDict = tableEntries[0].ToObject<Dictionary<dynamic, dynamic>>();
                for (int k = 0; k < entryDict.Keys.Count; k++)
                {
                    String key = entryDict.Keys.ToList()[k];
                    Console.WriteLine(key);
                }
            }
      
            }

    }
}

我在String key = entryDict.Keys.ToList()[k]; 线上遇到错误

Exception thrown: 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' in System.Linq.Expressions.dll An unhandled exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Linq.Expressions.dll 'System.Collections.Generic.Dictionary&lt;object,object&gt;.KeyCollection' does not contain a definition for 'ToList'

我怎样才能让它运行?我对 C# 很陌生,所以也愿意用更好的方法来编写我的代码

【问题讨论】:

  • 最好只使用您已经解析的JObject,而不是所有那些字典
  • @CamiloTerevinto 知道了。将更多地研究 JObject。我最初很难从中获取键列表,最后只是转换为字典

标签: c# dictionary generics tostring


【解决方案1】:

错误信息告诉你 entryDict.Keys 没有函数 ToList() .Keys 是一个使用枚举器遍历它的密钥集合。你不能像数组/列表一样访问它。

你想要的是这个:

foreach (var key in results.Keys)
{
    Console.WriteLine(key.ToString());
}

【讨论】:

  • 那是一个很好的解决方案,但你没有解释错误。而且你还断言了一些不正确的东西。它失败的原因是因为你不能调用扩展方法动态表达式。换句话说,Keys 确实有一个ToList 方法,但它是一个扩展方法
【解决方案2】:

使用构造函数创建列表

List<string> keyList = new List<string>(entryDict.Keys);
for (int k = 0; k < entryDict.Keys.Count; k++){
    String key = keysList[k];
    Console.WriteLine(key);
}

【讨论】:

  • 出现错误The best overloaded method match for 'System.Collections.Generic.List&lt;string&gt;.List(int)' has some invalid arguments
猜你喜欢
  • 2020-12-31
  • 2014-09-09
  • 2018-03-30
  • 2016-01-24
  • 1970-01-01
  • 2012-01-16
  • 1970-01-01
  • 2020-06-06
  • 1970-01-01
相关资源
最近更新 更多