C# 将键/值对添加到字典中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9890822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding key/value pairs to a dictionary
提问by John Baum
i am using a dictionary to store some key value pairs and had a question on the best way to populate the dictionary. I need to do some other operations in order to find and add my key value pairs to my dictionary. After those operations i may have found a key/value to add to the dictionary or i could have found nothing. My question is how i should populate the dictionary. Should i use a function that returns a key value pair if found and otherwise an empty one contained within a dictionary.Add(function()) call? i dont want to add empty key/value pairs to the dictionary so im not sure how the return call for that function would work. Or should i pass the dictionary to the function and add to it if needed? like
我正在使用字典来存储一些键值对,并且对填充字典的最佳方法有疑问。我需要做一些其他操作才能找到我的键值对并将其添加到我的字典中。在这些操作之后,我可能找到了要添加到字典中的键/值,或者我什么也找不到。我的问题是我应该如何填充字典。我应该使用一个函数,如果找到则返回一个键值对,否则返回一个包含在 dictionary.Add(function()) 调用中的空函数吗?我不想将空的键/值对添加到字典中,所以我不确定该函数的返回调用将如何工作。或者我应该将字典传递给函数并在需要时添加它?喜欢
function(dictionary)
{ if (pair found) {dictionary.add(pair)}}
采纳答案by Shadow Wizard is Ear For You
Not sure what you ask here, but here is how I handle dictionary to either add or update a value based on a key:
不确定你在这里问什么,但这是我如何处理字典以添加或更新基于键的值:
string key = "some key here";
string value = "your value";
if (myDict.ContainsKey(key))
{
myDict[key] = value;
}
else
{
myDict.Add(key, value);
}
You can wrap this in a method if you like:
如果您愿意,可以将其包装在一个方法中:
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");
You can also use the TryGetValuemethod but can't see any obvious advantage in this.
您也可以使用该TryGetValue方法,但在这方面看不到任何明显的优势。
回答by Timmerz
your pseudo code is right.
你的伪代码是对的。
public void Process( bool add, Dictionary<string, string> dictionary )
{
if( add ) dictionary.Add( "added", "value" );
}
you could also use an extension method:
您还可以使用扩展方法:
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( );
}
}

