简体   繁体   English

C#:无法将列表中存储的值写入控制台

[英]C#: Can't write values stored in list to console

I have the following function that allows me to make REST request via this function:我有以下 function 允许我通过此 function 发出 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();
        }

The outcome from it is the following (see screenshot):结果如下(见截图): 在此处输入图像描述

Now, from this point现在,从这一点

In the next section I call GetData, I would like to select Value and Timestamp Variables to do other tasks, but I'm unable to (my attempts are in lines where myTest and myTest_2 are being declared):在下一节中,我调用 GetData,我想使用 select 值和时间戳变量来执行其他任务,但我无法(我的尝试在声明 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);
            
        }

But the outcome of myTest and myTest_2 are the following:但是 myTest 和 myTest_2 的结果如下:

System.Collections.Generic.List 1[System.String] System.Linq.Enumerable+SelectListIterator 2[SentiloSpoofer.SensorContent,System.Collections.Generic.List`1[System.Char]] System.Collections.Generic.List 1[System.String] System.Linq.Enumerable+SelectListIterator 2[SentiloSpoofer.SensorContent,System.ZA9FC91939A389C7C73E7A3.F

I'm thinking perhaps is best to call GetData outside of the Lambda and bypass these issues, but if I wanted to retrieve this data, what could be a good way to do so?我想也许最好在 Lambda 之外调用 GetData 并绕过这些问题,但如果我想检索这些数据,有什么好的方法呢?

It's just the way you are writing to the console.这就是您写入控制台的方式。 Use string.Join or a foreach .使用string.Joinforeach

Essentially, you are trying to magic the values out of a list.本质上,您正在尝试将值从列表中变出。 Technically List<T> doesn't have an override of ToString() that knows how you want to format it.从技术上讲, List<T>没有对ToString()覆盖,它知道您要如何格式化它。 It's up to you.由你决定。 So it just returns the type name (which is what you are seeing).所以它只返回类型名称(这就是您所看到的)。

Try instead:请尝试:

foreach(var value in myTest)
  Console.WriteLine(value);

// or
Console.WriteLine(string.Join(",",myTest));

You are trying to access a List as a String.您正在尝试将列表作为字符串访问。 The values are there if you wanna show it in your console, just use an aggregate in your List.如果您想在控制台中显示这些值,只需在列表中使用聚合即可。

Example:例子:

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

// Or

myTest.ForEach(x => Console.WriteLine(x));

在 C# 中,为什么不能有一个 List<string> object 被存储在一个列表中<object>多变的<div id="text_translate"><p>似乎列表 object 不能存储在 C# 的列表变量中,甚至不能以这种方式显式转换。</p><pre> List&lt;string&gt; sl = new List&lt;string&gt;(); List&lt;object&gt; ol; ol = sl;</pre><p> 导致无法将类型System.Collections.Generic.List&lt;string&gt;隐式转换为System.Collections.Generic.List&lt;object&gt;</p><p> 接着...</p><pre> List&lt;string&gt; sl = new List&lt;string&gt;(); List&lt;object&gt; ol; ol = (List&lt;object&gt;)sl;</pre><p> 导致无法将类型System.Collections.Generic.List&lt;string&gt;转换为System.Collections.Generic.List&lt;object&gt;</p><p> 当然,您可以通过将所有内容从字符串列表中拉出并一次将其放回其中来做到这一点,但这是一个相当复杂的解决方案。</p></div></object></string> - In C#, why can't a List<string> object be stored in a List<object> variable

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C#-无法将列表写入txt文件 - C# - Can't write list into the txt file 在控制台应用程序C#中调用存储过程值 - Calling stored procedure values into the console application C# 从Powershell ISE调用时无法以异步C#代码写入控制台 - Can't write to console in async C# code when called from powershell ISE 为什么在 Visual Studio for C# 上启动控制台应用程序后无法编写任何代码? - Why can't I write any code after starting a console application on Visual Studio for C#? 无法将值添加到列表(计数始终为1)-C# - Can't add values to List (Count is always 1) - C# 无法在属性列表C#中打印值 - can't print values inside of the property list c# 如何在C#控制台应用程序中编写包含多个值的常量? - How to Write Constants Containing Multiple Values in C# Console App? 在 C# 中,为什么不能有一个 List<string> object 被存储在一个列表中<object>多变的<div id="text_translate"><p>似乎列表 object 不能存储在 C# 的列表变量中,甚至不能以这种方式显式转换。</p><pre> List&lt;string&gt; sl = new List&lt;string&gt;(); List&lt;object&gt; ol; ol = sl;</pre><p> 导致无法将类型System.Collections.Generic.List&lt;string&gt;隐式转换为System.Collections.Generic.List&lt;object&gt;</p><p> 接着...</p><pre> List&lt;string&gt; sl = new List&lt;string&gt;(); List&lt;object&gt; ol; ol = (List&lt;object&gt;)sl;</pre><p> 导致无法将类型System.Collections.Generic.List&lt;string&gt;转换为System.Collections.Generic.List&lt;object&gt;</p><p> 当然,您可以通过将所有内容从字符串列表中拉出并一次将其放回其中来做到这一点,但这是一个相当复杂的解决方案。</p></div></object></string> - In C#, why can't a List<string> object be stored in a List<object> variable 在C#中填充List a-sync和console.write进度 - Populate a List a-sync and console.write progress in C# 如果被中断,C#Console.Out()不会写入 - C# Console.Out() doesn't write if interrupted
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM