如何更改字典的值

时间:2012-06-16 14:35:50

标签: c# .net windows

我有一本字典

public static IDictionary<string, IList<string>> checksCollection = 
           new Dictionary<string, IList<string>>();

我按如下方式添加到词典中:

public static void addCheck(string checkName, string hostName, 
          string port, string pollInterval, string alertEmail, 
          string alertSMS, string alertURI)
{
    checksCollection.Add(checkName, new[] { checkName, hostName, port, 
               pollInterval, alertEmail, alertSMS, alertURI });
}

如何更改alertURI列表值?

2 个答案:

答案 0 :(得分:1)

最快的方法是从字典中获取IList<string>并访问其第七个元素:

checksCollection[checkName][6] = "new value";

但如果我是你,我会将字符串数组中的所有值都设置为自己的类,这样您就不必对索引值进行硬编码,以防您以后添加或删除其他属性。像这样创建一个类定义:

public class YourClass
{
    public string CheckName { get; set; }
    public string HostName { get; set; }
    public string Port { get; set; }
    public string PollInterval { get; set; }
    public string AlertEmail { get; set; }
    public string AlertSMS { get; set; }
    public string AlertURI { get; set; }
}

并更改字典定义:

public static IDictionary<string, YourClass> checksCollection = 
    new Dictionary<string, YourClass>();

然后添加到它(尽管最好你会在YourClass上创建一个带有参数的构造函数):

public static void addCheck(string checkName, string hostName, string port, string pollInterval, string alertEmail, string alertSMS, string alertURI)
{
    checksCollection.Add(checkName, new YourClass() { 
        CheckName = checkName,
        HostName = hostName,
        Port = port,
        PollInterval = pollInterval,
        AlertEmail = alertEmail,
        AlertSMS = alertSMS,
        AlertURI = alertURI
    });
}

然后修改变得简单,没有猜测数组索引:

checksCollection[checkName].AlertURI = "new value";

答案 1 :(得分:0)

一种方法是做

checksCollection["somekey"][6] = "new value for alertURI"

我建议创建一个代表这7个值的小对象,比如

class Foo {
    public string HostName { get; set; }
    public string Port { get; set; }
    public string PollInterval { get; set; }
    public string AlertEmail { get; set; }
    public string AlertSMS { get; set; } 
    public string AlertURI { get; set; }
}

然后你可以通过

改变它
checksCollection["key"].AlertURI = "something else";