-1

I have a code that lists all 38 weather data using a foreach() from openweathermap.org (JSON). I would like to have only the next number of first x entries in foreach() to give xh forecast. Where x may be 3 or something that low.

Here is my code I have so far:

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

This is the output it generates (time is in 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%
[...]
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
nolimits
  • 43
  • 1
  • 3
  • 16

1 Answers1

3

Use the Take() method to only take the first n items from the list:

foreach (var json in myweather.list.Take(n))
Greg Sansom
  • 20,442
  • 6
  • 58
  • 76