[英]List only prints last element
I'm new to c# and appreciate all the help i can get.我是 c# 的新手,感谢我能得到的所有帮助。 Programs works, but I have this problem where I want to print all countries (3 countries) in a list but I only get the last country as output.
程序有效,但我有这个问题,我想在列表中打印所有国家(3 个国家),但我只得到最后一个国家作为 output。
How do I print all the countries in a list?如何打印列表中的所有国家/地区?
Main window:主要 window:
public void euHourly()
{
List<Tuple<string, string>> euHourly = new List<Tuple<string, string>>();
euHourly.Add(Tuple.Create("Riga", "https://api.openweathermap.org/data/2.5/onecall?lat=57&lon=23&units=metric&exclude=current,minutely,hourly,alerts&appid=e4ef2ac494977d735811075476bcc0bf"));
euHourly.Add(Tuple.Create("Tallinn", "https://api.openweathermap.org/data/2.5/onecall?lat=59.43&lon=24.75&units=metric&exclude=current,minutely,hourly,alerts&appid=e4ef2ac494977d735811075476bcc0bf"));
euHourly.Add(Tuple.Create("Moscow", "https://api.openweathermap.org/data/2.5/onecall?lon=37.61&lat=55.75&units=metric&exclude=current,minutely,hourly,alerts&appid=e4ef2ac494977d735811075476bcc0bf"));
foreach (var link in euHourly)
{
var filepath = Orai.Default.txtBox + "\\Europe.txt";
StreamWriter sw = File.CreateText(filepath);
sw.Close();
StreamWriter file = new StreamWriter(new FileStream(filepath, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite), Encoding.UTF8);
try
{
List<Tuple<string, string>> url = getData.euDataDaily(link.Item2);
file.WriteLine("City;Temperature;Icon");
foreach (var tuple in url)
{
try
{
file.WriteLine(link.Item1 + ";" + tuple.Item1 + ";" + tuple.Item2) ;
}
catch
{
MessageBox.Show("No data");
}
}
file.Close();
pbStatus.Dispatcher.Invoke(() => pbStatus.Value = pbStatus.Value + 5, DispatcherPriority.Background);
}
catch
{
MessageBox.Show("No data");
}
}
}
getData window:获取数据 window:
public static List<Tuple<string, string>> euDataDaily(string url)
{
var aTuple = new List<Tuple<string, string>> { };
WebClient c = new WebClient();
var data = c.DownloadString(url);
JObject o = JObject.Parse(data);
string conditionCode="";
string unixDate = "";
string dayTemp="";
foreach (var result in o["daily"])
{
unixDate = (string)result["dt"];
if (unixDate.Equals("1617786000"))
{
dayTemp = (string)result["temp"]["day"];
}
if (unixDate.Equals("1617786000"))
{
foreach (var resultas in result["weather"])
{
conditionCode = (string)resultas["description"];
}
}
}
aTuple.Add(Tuple.Create(dayTemp, conditionCode));
return aTuple;
}
Europe.txt欧洲.txt
City;Temperature;Icon
Moscow;9.32;light rain
Also I'm new to this website.我也是这个网站的新手。 If anything is inappropriate with my question, let me know.
如果我的问题有任何不妥之处,请告诉我。 Thanks for all help:).
感谢所有帮助:)。
You create the file 3 times.您创建文件 3 次。 You need to move
File.CreateText
and related code (eg the file header) outside of the foreach
.您需要将
File.CreateText
和相关代码(例如文件头)移到foreach
之外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.