如何更改字典的值

本文关键字:字典 何更改 | 更新日期: 2023-09-27 18:37:21

我有字典

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列表值?

如何更改字典的值

最快的方法,从字典中获取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";

一种方法是这样做

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";