【发布时间】:2018-08-09 00:41:28
【问题描述】:
我正在创建一个存储和显示天气详细信息的应用程序。
在这个 sn-p result 是一个对象列表(40 个对象,5 天内每天 8 个天气预报),我将其分为天和小时。我正在使用嵌套列表来显示天列表中的每小时预测列表(每个 sortedDay 列表中都有自己的 sortedHours 列表。
当我打印输出时,每个对象都具有相同的值,并且每次打印后都会调用 Debug.WriteLine(" -");(39 次,但最多只能调用 5 次)
//create a list of weatherController lists to hold each day
List<List<WeatherController>> sortedDays =new List<List<WeatherController>>();
//create a list of weatherController objects to hold each hourly interval
List<WeatherController> sortedHours = new List<WeatherController>();
// a base time
DateTime prevDate = Convert.ToDateTime("2000-01-01");
int counter = 0;
// iterate through result list
foreach (var wCount in result.list)
{
// if the date is greater than the previous date add the sortedHours to sortedDays
if (Convert.ToDateTime(result.list[counter].dt_txt) > prevDate && counter!=0)
{
sortedDays.Add(sortedHours);
sortedHours.Clear();
}
WeatherController wController= new WeatherController();
wController.dtime=result.list[counter].dt_txt;
wController.temp = result.list[counter].main.temp;
wController.humidity= result.list[counter].main.humidity;
wController.desc = result.list[counter].weather[0].description;
wController.windSpeed= result.list[counter].wind.speed;
sortedHours.Add(wController);
prevDate = Convert.ToDateTime(result.list[counter].dt_txt);
counter++;
}
// test List of list Structure
int xCount=0,yCount=0;
foreach(var sd in sortedDays)
{
foreach(var sh in sortedHours)
{
// DEBUG
Debug.WriteLine(sortedDays[xCount][yCount].ToString());
yCount++;
}
Debug.WriteLine(" -");
xCount++;
yCount = 0;
}
输出的一个sn-p:
dtime:2018-03-05 21:00:00 temp:274.687 humidity:100 desc:light rain windpeed:3.61
-
dtime:2018-03-05 21:00:00 temp:274.687 humidity:100 desc:light rain windpeed:3.61
-
dtime:2018-03-05 21:00:00 temp:274.687 humidity:100 desc:light rain windpeed:3.61
-
dtime:2018-03-05 21:00:00 temp:274.687 humidity:100 desc:light rain windpeed:3.61
-
【问题讨论】:
-
您为什么使用
foreach,然后不使用wCount(或sd,或sh)?您不妨只使用for循环... -
由于数据是从api读取的,所以大小可能会发生变化,而且wCount是一个对象而不是整数值,也会被拆分成单独的方法
-
我知道,我的意思是你可以使用
wCount而不是result.list[counter]。大小是result.list.Length(或.Count()),对吧……? -
哦,对了,我觉得这不是问题,因为当我调试它时,它会从
result获取正确的值并将它们正确分配给wController,但问题似乎出在何时它被添加到列表中 -
对,这只是为了让您的代码更易于阅读而考虑的事情
标签: c# list object uwp nested-loops