【问题标题】:Adding key/value pairs to a dictionary将键/值对添加到字典
【发布时间】:2012-03-27 13:47:27
【问题描述】:

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

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

【问题讨论】:

  • 为什么不使用原生 Dictionary?它已经管理存储,具有用于检查密钥存在的 ContainsKey 方法,并且您可以在其上使用 LINQ 来返回 KeyValuePair 条目?
  • 我正在寻找填充 Dictionary 对象的最佳方法。为了填充它,我需要执行一些其他操作来提出要放置在字典中的对象。因此,我应该将这些操作推送到一个方法并让它返回一个键值对然后添加到 dic 中吗?或者如果找到任何值,我应该传递新创建的 dict 并将其传递给函数以添加到它?
  • 这真的取决于你想用这个方法做什么,以及它是否应该有这个能力。根据我的理解,我只会推入字典,然后让该方法发挥作用。这将是最容易实现的。
  • 使用第二个选项 - 将字典传递给您的方法。我不知道可以传递给字典的 add 方法的值,它不会导致添加。
  • 你的问题留下了很大的假设空间,所以没有好的方法来回答它。从我读过的内容来看,您应该使用更像第二种方法的东西(仅在找到匹配项时才向字典添加内容),但我仍然认为如果您提供更多详细信息,我们可以将其清理得更多(就像你正在使用的代码一样)。

标签: c#


【解决方案1】:

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

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 方法,但看不到任何明显的优势。

【讨论】:

  • 也许我遗漏了一些东西,但 dict[key]=value 要么添加要么更新值(集合调用“private void Insert(TKey key, TValue value, bool add)”)。
  • @user276648 我是唯一一个缺乏理智的人,你完全正确!我曾经在经典的 ASP 中使用字典,并猜测语法只是卡住了。随意以这种简单的方式发布新答案,以便其他人了解二传手。
【解决方案2】:

你的伪代码是对的。

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( );
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 2023-03-31
    • 2011-04-16
    • 1970-01-01
    • 2017-11-15
    • 2011-07-17
    相关资源
    最近更新 更多