首先,我在列表中存储多个值。我想从消息框中获取列表输出中的所有元素,但它不起作用!我也尝试了许多方式,使得foreach循环在消息框下但不起作用。请帮帮我。The code is for message box. First is my code output and second is target output
答案 0 :(得分:4)
此代码可以帮助您执行此操作:
让@RequestMapping(method = RequestMethod.POST)
public String weatherPost(@ModelAttribute City city, ModelMap model) throws URISyntaxException{
String apiKey="myApIKey";//Removed my original API Key for posting.
RestTemplate template = new RestTemplate();
String strUri= "http://api.openweathermap.org/data/2.5/weather?q="+city.getName()+",AU&appid="+apiKey+"&units=metric";
URI uri = new URI(strUri);
RequestEntity<String> request = new RequestEntity<String>(HttpMethod.GET,uri);
ResponseEntity <WeatherResponse> weatherResponse = template.exchange(uri, HttpMethod.GET, request, WeatherResponse.class);
City myCity = new City();
model.put("weatherResponse", weatherResponse);
model.put("city", myCity);
return "weather";
}
成为您已经拥有的字符串列表,您可以使用String.Join()
方法来加入用分隔符分隔的字符串(这里我选择MyListValues
作为分隔符)。现在看一下这个片段:
,
对于您的特定示例,最佳选项是在Student类中覆盖.ToString()
方法。
对于使用类定义可能如下所示:
List<string>MyListValues= new List<string>(){"value 1","value 2","value 3","value 4","value 10","value 11"};
string delimiter=",";
string messageBoxContent=String.Join(delimiter,MyListValues);
MessageBox.Show(messageBoxContent);
你的列表迭代将是:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string email { get; set; }
// rest of properties and declarations
//Class methods and constructors
public override string ToString()
{
StringBuilder ObjectString = new StringBuilder();
ObjectString.AppendLine("Stdent Details");
ObjectString.AppendLine("Name :" + this.Name);
ObjectString.AppendLine("ID :" + this.Id);
ObjectString.AppendLine("Email :" + this.email);
return ObjectString.ToString();
}
}
或者
foreach (Student student in StudentList)
{
MessageBox.Show(student.ToString());// Shows the message in each iteration
}
答案 1 :(得分:3)
将str
圈内的foreach
变量更改为:
str += students.studentRegNo+ " " + students.studentName + " " + students.studentEmail+ Environment.NewLine;