【问题标题】:C#: Can't write values stored in list to consoleC#:无法将存储在列表中的值写入控制台
【发布时间】:2020-08-20 23:49:56
【问题描述】:

我有以下函数允许我通过这个函数发出 REST 请求:

static Observation GetData(string baseUrl, string provider, string key, string sensor)
        {
            var client = new RestClient(String.Format("{0}/data/{1}/{2}", baseUrl, provider, sensor));
            client.Timeout = -1;
            var request = new RestRequest(Method.GET);
            request.AddHeader("IDENTITY_KEY", key);
            IRestResponse response = client.Execute(request);
            Console.WriteLine(response.Content);
            
            var observationsModel = JsonSerializer.Deserialize<SentiloResponse>(response.Content, options);
            Console.WriteLine("This is observationsModel:");
            Console.WriteLine(observationsModel);
            Console.WriteLine("This is the outcome of GetData:");
            Console.WriteLine(observationsModel.Observations.FirstOrDefault());
            return observationsModel.Observations.FirstOrDefault();
        }

它的结果如下(见截图):

现在,从这里开始

在下一部分我调用 GetData,我想选择值和时间戳变量来执行其他任务,但我无法(我的尝试在声明 myTest 和 myTest_2 的行中):

static void Main(string[] args)
        {
            configuration = JsonSerializer.Deserialize<SentiloConfig>(File.ReadAllText("configuration.json"), options);
            Console.WriteLine("Configuration Loaded");
            
            foreach(var componentMapping in configuration.ComponentMappings)
            {
                var inputComponent = componentMapping.InputComponent;
                Console.WriteLine("Getting data");
                var sensorsContent = inputComponent.Sensors.AsParallel().Select(s =>
                    new SensorContent{
                        Sensor = GetSensorString(s.SensorName),
                        Observations = new List<Observation>() {
                                
                            GetData(
                                    inputComponent.ServerUrl,
                                    inputComponent.Provider,
                                    inputComponent.Token,
                                    GetSensorString(s.SensorName)
                                    )
                                
                        }
                    }
                ).Where(s => s.Observations.First() != null).ToList();
                var myTest = sensorsContent.Select(s => s.Observations.First().Value).ToList();
                var myTest_2 = sensorsContent.Select(s => s.Observations.First().Value.ToList());
                Console.WriteLine(myTest.ToString());
                Console.WriteLine(myTest_2);
                Console.WriteLine("data retrieved");
                if (!sensorsContent.Any())
                {
                    Console.WriteLine("No sensor data for component {0} with sensors: {1}, check configuration", inputComponent.ComponentName, string.Join(",", inputComponent.Sensors.Select(s => s.SensorName)));
                    continue;
                }
                var sensorRequest = new SentiloPutRequest { Sensors = sensorsContent };
                    
            }
            System.Threading.Thread.Sleep(configuration.SendTime*1000);
            
        }

但 myTest 和 myTest_2 的结果如下:

System.Collections.Generic.List1[System.String] System.Linq.Enumerable+SelectListIterator2[SentiloSpoofer.SensorContent,System.Collections.Generic.List`1[System.Char]]

我在想也许最好在 Lambda 之外调用 GetData 并绕过这些问题,但如果我想检索这些数据,有什么好的方法呢?

【问题讨论】:

    标签: c# list lambda


    【解决方案1】:

    这就是您写入控制台的方式。使用string.Joinforeach

    本质上,您是在尝试将值从列表中变出。从技术上讲,List&lt;T&gt; 没有ToString()覆盖,它知道您要如何格式化它。由你决定。所以它只返回类型名称(这就是您所看到的)。

    试试吧:

    foreach(var value in myTest)
      Console.WriteLine(value);
    
    // or
    Console.WriteLine(string.Join(",",myTest));
    

    【讨论】:

    • 非常感谢,迈克尔!有效。我的问题是我对 C# 太缺乏经验,我最接近它的是 C++,之后只有 Python 或 Matlab。我必须承认,当你说我试图用魔法改变价值观时,我笑了很多,嗯,确实是我的朋友(我把它归咎于我对 Python 和其他语言的经验,哈哈哈;))。好的,现在回到严肃点。这意味着我成功地将这些值分配到 myTest var 中,对吧?
    【解决方案2】:

    您正试图以字符串的形式访问列表。 如果您想在控制台中显示这些值,只需在列表中使用聚合即可。

    例子:

    var myTestString = myTest.Select(i => i).Aggregate((i, j) => i + "," + j);
    Console.WriteLine(myTestString)
    
    // Or
    
    myTest.ForEach(x => Console.WriteLine(x));
    

    【讨论】:

    • Select(i=&gt;i) 毫无意义,因为它什么都不做,string.Join 比使用 Aggregate 更好,因为它以更有效的方式处理创建字符串。
    猜你喜欢
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多