具有多个值的ArrayList c#

Kly*_*roe 1 c# arrays dictionary arraylist

我不确定这是否可以使用ArrayList或Dictionary,或者它是否是其他东西,如果是这样我想知道你在哪里可以指出我正确的方向......

你有一个具有多个值的ArrayList,即

ArrayList weather = new ArrayList();
weather.Add("Sunny", "img/sunny.jpg");
weather.Add("Rain", "img/Rain.jpg);
Run Code Online (Sandbox Code Playgroud)

然后分配给下面的控件.

if (WeatherValue = 0)
{
   Label1.Text = weather[0].ToString;
   Image1.ImageUrl = weather[0].ToString;
}
Run Code Online (Sandbox Code Playgroud)

或者我可以用词典做到这一点

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
Run Code Online (Sandbox Code Playgroud)

如何使用[0]和[1]分别调用字典的值?等等

Tim*_*ter 7

没有理由继续使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后您可以使用这个可读且可维护的代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

更新:根据您编辑的问题.字典没有多大意义,因为您无法通过索引(它没有订单)访问它,只能通过密钥访问它.因为这将是天气名称,你必须事先知道它.但似乎你没有它.

因此,要么循环字典中的所有键值对,要使用键作为名称和路径的值,或者只使用一个更好的真实类.

如果你不想创建一个类,我脑子里只有一件事,那就是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;
}
Run Code Online (Sandbox Code Playgroud)

  • 也许把'Name'变成一个名为weatherType的枚举? (2认同)