将键/值对添加到字典中

时间:2012-03-27 13:47:27

标签: c#

我正在使用字典存储一些键值对,并对填充字典的最佳方法有疑问。我需要做一些其他操作才能找到并将我的键值对添加到我的字典中。在那些操作之后,我可能已经找到了要添加到字典中的键/值,或者我找不到任何内容。我的问题是我应该如何填充字典。我应该使用一个函数来返回一个键值对,如果找到,否则一个空的一个包含在dictionary.Add(function())调用?我不想在字典中添加空键/值对,所以我不确定该函数的返回调用是如何工作的。或者我应该将字典传递给函数并在需要时添加它?喜欢

function(dictionary) 
{ if (pair found) {dictionary.add(pair)}}

2 个答案:

答案 0 :(得分:15)

不确定你在这里问什么,但这里是我如何处理字典以根据键添加或更新值:

string key = "some key here";
string value = "your value";
if (myDict.ContainsKey(key))
{
    myDict[key] = value;
}
else
{
    myDict.Add(key, value);
}

如果您愿意,可以将其包装在一个方法中:

void AddOrUpdate(Dictionary<string, string> dict, string key, string value)
{
    if (dict.ContainsKey(key))
    {
        dict[key] = value;
    }
    else
    {
        dict.Add(key, value);
    }
}

//usage:
AddOrUpdate(myDict, "some key here", "your value");

你也可以使用TryGetValue方法,但在这方面看不到任何明显的优势。

答案 1 :(得分:3)

你的伪代码是对的。

public void Process( bool add, Dictionary<string, string> dictionary )
{
   if( add ) dictionary.Add( "added", "value" );
}

你也可以使用扩展方法:

static class Program
{
    public static void AddIfNotNull(this Dictionary<string,object> target, string key, object value )
    {
        if( value != null )
            target.Add( key, value );
    }

    static void Main(string[] args)
    {
        var dictionary = new Dictionary<string, object>( );

        dictionary.AddIfNotNull( "not-added",    null );
        dictionary.AddIfNotNull( "added",       "true" );

        foreach( var item in dictionary )
            Console.WriteLine( item.Key );

        Console.Read( );
    }

}
相关问题