【发布时间】:2019-12-24 00:20:25
【问题描述】:
我有一个代码,它使用来自 openweathermap.org (JSON) 的 foreach() 列出了所有 38 个天气数据。我希望在 foreach() 中只有 前 x 个条目来提供 xh 预测。其中 x 可能是 3 或那么低的值。
这是我目前的代码:
namespace ConsoleApp2
{
public class RootObject
{
public List<myWeather> list { get; set; }
}
public class myWeather
{
public Main main { get; set; }
public Clouds clouds { get; set; }
public string dt_txt { get; set; }
}
public class Main
{
public float temp { get; set; }
public float humidity { get; set; }
}
public class Clouds
{
public float all { get; set; }
}
class Program
{
static void Main()
{
using (WebClient client = new WebClient())
{
Console.WriteLine("ACCESSING jsonWeather ...");
string jsonWeather = client.DownloadString("http://api.openweathermap.org/data/2.5/forecast?q=Auckland,NZ&APPID=45c3e583468bf450fc17026d6734507e");
var myweather = JsonConvert.DeserializeObject<RootObject>(jsonWeather);
string localtime = DateTime.Now.TimeOfDay.ToString();
foreach (var json in myweather.list) /// how to limit the number of data to x coming out here?
{
Console.WriteLine(json.dt_txt);
Console.WriteLine(json.clouds.all);
Console.WriteLine(json.main.temp);
Console.WriteLine(json.main.humidity);
}
Console.ReadLine();
}
}
}
}
这是它生成的输出(时间为 UTC):
ACCESSING jsonWeather ...
Time 2019-12-24 03:00:00
Coverage 7
20.7499938964844
50%
Time 2019-12-24 06:00:00
Coverage 3
17.8300109863281
66%
Time 2019-12-24 09:00:00
Coverage 0
12.9699951171875
89%
Time 2019-12-24 12:00:00
Coverage 0
12.7700134277344
93%
Time 2019-12-24 15:00:00
Coverage 21
13.4299865722656
94%
Time 2019-12-24 18:00:00
Coverage 48
15.0500122070313
89%
Time 2019-12-24 21:00:00
Coverage 81
19.4999938964844
66%
Time 2019-12-25 00:00:00
Coverage 63
22.8300109863281
51%
Time 2019-12-25 03:00:00
Coverage 0
21.5700012207031
57%
Time 2019-12-25 06:00:00
Coverage 0
18.9399963378906
67%
Time 2019-12-25 09:00:00
Coverage 3
13.7499938964844
92%
Time 2019-12-25 12:00:00
Coverage 8
13.2000061035156
92%
Time 2019-12-25 15:00:00
Coverage 33
12.9399963378906
93%
[...]
【问题讨论】:
-
所以你只想要
list.Take(x)? -
这个副本回答了你的问题:How to get first N elements of a list in C#?
-
如果你知道你只想要 3,为什么不直接使用基本的 for 循环呢?