2016-03-17 42 views
1

我不能確定這是否是可能的ArrayList或解釋,或是否會是別的東西,如果是的話我不知道,你可以在正確的方向點我...ArrayList中有多個值C#

燦你有一個ArrayList有多個值,即

ArrayList weather = new ArrayList(); 
weather.Add("Sunny", "img/sunny.jpg"); 
weather.Add("Rain", "img/Rain.jpg); 

爲了然後分配到控制像下面。

if (WeatherValue = 0) 
{ 
    Label1.Text = weather[0].ToString; 
    Image1.ImageUrl = weather[0].ToString; 
} 

或者,我可以做到這一點用字典

Dictionary<string, string> dict = new Dictionary<string, string>(); 
dict.Add("Cloudy", "../img/icons/w0.png"); //[0] 
dict.Add("Rain", "../img/icons/w1.png"); //[1] 

Label1.Text = dict[0].VALUE1; //So this would get Cloudy 
Image.ImageUrl = dict[0].VALUE2; //This would get ../img/w0.png 

你如何稱呼一個字典的值分別使用[0]和[1]?等

+1

Theres沒有理由仍然使用'ArrayList',使用'System.Collections.Generic.List ' -class –

回答

5

沒有理由仍然使用ArrayList,使用System.Collections.Generic.List<T>-class。然後,您保持編譯時的安全,並且不需要投下所有東西。

在這種情況下,你應該創建一個自定義類:

public class Weather 
{ 
    public double Degree { get; set; } 
    public string Name { get; set; } 
    public string IconPath { get; set; } 

    public override string ToString() 
    { 
     return Name; 
    } 
} 

然後你就可以使用這個可讀和可維護的代碼:

List<Weather> weatherList = new List<Weather>(); 
weatherList.Add(new Weather { Name = "Sunny", IconPath = "img/sunny.jpg" }); 
weatherList.Add(new Weather { Name = "Rain", IconPath = "img/Rain.jpg" }); 

if (WeatherValue == 0) // whatever that is 
{ 
    Label1.Text = weatherList[0].Name; 
    Image1.ImageUrl = weatherList[0].IconPath; 
} 

更新:根據您的編輯問題。字典沒什麼意義,因爲你不能通過索引訪問它(它沒有順序),而只能通過鍵來訪問它。因爲那將是你必須事先知道的天氣名稱。但似乎你沒有它。

因此,要麼循環字典中的所有鍵 - 值對,並使用該鍵作爲名稱和路徑的值,或者只是使用真實的類,這會更好。

如果你不想創建一個類只有一個是在我腦海中的東西,Tuple

List<Tuple<string, string>> weatherList = new List<string, string>(); 
weatherList.Add(Tuple.Create("Sunny", "img/sunny.jpg")); 
weatherList.Add(Tuple.Create("Rain", "img/Rain.jpg")); 

if (WeatherValue == 0) // whatever that is 
{ 
    Label1.Text = weatherList[0].Item1; 
    Image1.ImageUrl = weatherList[0].Item2; 
} 
+2

也許把'Name'變成一個名爲weatherType的枚舉? – sr28

+0

@ sr28:當然,有很多方法可以改進或擴展這個類。它應該給OP一個想法。 –

+0

我也會創建自己的課程。但接下來還有可以使用的Tuple類 – Fredrik

0

您可以使用字典

Dictionary<string, string> weather = new Dictionary<string, string>(); 

values.Add("Sunny", "img/sunny.jpg"); 
values.Add("Rain", "img/Rain.jpg"); 

以最簡單的方法呼叫元素在一個字典中使用foreach循環

foreach (var pair in weather) 
    { 
     Console.WriteLine("{0}, {1}",pair.Key,pair.Value); 
    }