2014-01-13 77 views
0

所以我完全不熟悉編程;我已經閱讀了許多類似的問題和相應的答案,並且花費了更多的時間,而不是我想承認嘗試不同的方式來解決我的問題,但我似乎無法找到問題所在。無論如何,這是我的代碼:將結構存儲在列表中,然後顯示列表?

public struct City 
{ 
    public string cityName { get; set; } 
    public float cityTemp { get; set; } 
} 
class Program 
{ 
    static void Main(string[] args) 
    { 
     var cityList = new List<City>(); 
     cityList.Add(new City 
     { 
      cityName = "Stockholm", 
      cityTemp = 22.65f 
     }); 
     Console.WriteLine("List: "); 
     Console.WriteLine(cityList); 
     Console.ReadKey(); 
    } 
} 

如何使列表存儲我的結構,以及如何正確顯示列表? 編輯:我知道我需要使用foreach,這個代碼只是我的問題的準系統表示。

回答

2

你想是這樣的:

public struct City 
{ 
    public string cityName { get; set; } 
    public float cityTemp { get; set; } 
} 
class Program 
{ 
    static void Main(string[] args) 
    { 
     var cityList = new List<City>(); 
     cityList.Add(new City 
     { 
      cityName = "Stockholm", 
      cityTemp = 22.65f 
     }); 
     cityList.Add(new City 
     { 
      cityName = "London", 
      cityTemp = 25.24f 
     });   
     Console.WriteLine("List: "); 
     foreach (var city in cityList) 
     { 
      Console.WriteLine(string.Format("City: {0} is currently: {1}oC", city.cityName, city.cityTemp); 
     } 
     Console.ReadKey(); 
    } 
} 

您還可以通過重寫ToString()這樣讓你的城市輸出一個明智的迴應:

public struct City 
{ 
    public string cityName { get; set; } 
    public float cityTemp { get; set; } 
    public override string ToString() 
    { 
     return String.Format("City: {0} is currently: {1}oC", cityName, cityTemp); 
    } 
} 

,那麼你可以有:

class Program 
{ 
    static void Main(string[] args) 
    { 
     var cityList = new List<City>(); 
     cityList.Add(new City 
     { 
      cityName = "Stockholm", 
      cityTemp = 22.65f 
     }); 
     cityList.Add(new City 
     { 
      cityName = "London", 
      cityTemp = 25.24f 
     });   
     Console.WriteLine("List: "); 
     foreach (var city in cityList) 
     { 
      Console.WriteLine(city); 
     } 
     Console.ReadKey(); 
    } 
} 
+0

完美,string.Format(...)是我一直在尋找的! – Welsing

1

列表存儲您的結構。至於展示他們,這不符合魔法。您必須遍歷列表並顯示每個列表。

public struct City 
{ 
    public string cityName { get; set; } 
    public float cityTemp { get; set; } 
    public override string ToString() 
    { 
     return String.Format("{0} {1}", cityName, cityTemp); 
    } 
} 

public void DisplayAll(IEnumerable<City> cities) 
{ 
    foreach (var city in cities) 
     Console.WriteLine(city); 
} 
0

您需要遍歷城市列表以顯示它們:

Console.WriteLine("List: "); 

foreach(var city in cityList) 
{ 
    Console.WriteLine(city.cityName + " " + city.cityTemp); 
} 
相關問題