有没有一个更优雅的方式来添加一个词典<>安全?(Is there a more elegant way of adding an item to a Dictionary<> safely?)

我需要在字典中添加键/对,但是我当然需要首先检查密钥是否已经存在,否则我得到一个“ 密码已经存在于字典 ”中。 下面的代码解决了这个,但是很笨重。

这样做一个更优雅的方式,而不需要像这样的字符串帮助方法?

using System; using System.Collections.Generic; namespace TestDictStringObject { class Program { static void Main(string[] args) { Dictionary<string, object> currentViews = new Dictionary<string, object>(); StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view1"); StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view2"); StringHelpers.SafeDictionaryAdd(currentViews, "Employees", "view1"); StringHelpers.SafeDictionaryAdd(currentViews, "Reports", "view1"); foreach (KeyValuePair<string, object> pair in currentViews) { Console.WriteLine("{0} {1}", pair.Key, pair.Value); } Console.ReadLine(); } } public static class StringHelpers { public static void SafeDictionaryAdd(Dictionary<string, object> dict, string key, object view) { if (!dict.ContainsKey(key)) { dict.Add(key, view); } else { dict[key] = view; } } } }

I need to add key/object pairs to a dictionary, but I of course need to first check if the key already exists otherwise I get a "key already exists in dictionary" error. The code below solves this but is clunky.

What is a more elegant way of doing this without making a string helper method like this?

using System; using System.Collections.Generic; namespace TestDictStringObject { class Program { static void Main(string[] args) { Dictionary<string, object> currentViews = new Dictionary<string, object>(); StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view1"); StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view2"); StringHelpers.SafeDictionaryAdd(currentViews, "Employees", "view1"); StringHelpers.SafeDictionaryAdd(currentViews, "Reports", "view1"); foreach (KeyValuePair<string, object> pair in currentViews) { Console.WriteLine("{0} {1}", pair.Key, pair.Value); } Console.ReadLine(); } } public static class StringHelpers { public static void SafeDictionaryAdd(Dictionary<string, object> dict, string key, object view) { if (!dict.ContainsKey(key)) { dict.Add(key, view); } else { dict[key] = view; } } } }

最满意答案

只需使用索引器 - 如果已经存在,它将覆盖,但不一定要先在其中:

Dictionary<string, object> currentViews = new Dictionary<string, object>(); currentViews["Customers"] = "view1"; currentViews["Customers"] = "view2"; currentViews["Employees"] = "view1"; currentViews["Reports"] = "view1";

如果键的存在表示一个错误(所以你想要它抛出)和索引器的基本上使用Add 。 (有点像铸造和使用之间的差异,参考转换。)

如果您使用C#3, 并且您有一个独特的键 ,您可以使这更加整洁:

var currentViews = new Dictionary<string, object>() { { "Customers", "view2" }, { "Employees", "view1" }, { "Reports", "view1" }, };

这在你的情况下不会奏效,因为集合初始化器总是使用Add将抛出第二个Customers条目。

Just use the indexer - it will overwrite if it's already there, but it doesn't have to be there first:

Dictionary<string, object> currentViews = new Dictionary<string, object>(); currentViews["Customers"] = "view1"; currentViews["Customers"] = "view2"; currentViews["Employees"] = "view1"; currentViews["Reports"] = "view1";

Basically use Add if the existence of the key indicates a bug (so you want it to throw) and the indexer otherwise. (It's a bit like the difference between casting and using as for reference conversions.)

If you're using C# 3 and you have a distinct set of keys, you can make this even neater:

var currentViews = new Dictionary<string, object>() { { "Customers", "view2" }, { "Employees", "view1" }, { "Reports", "view1" }, };

That won't work in your case though, as collection initializers always use Add which will throw on the second Customers entry.

有没有一个更优雅的方式来添加一个词典<>安全?(Is there a more elegant way of adding an item to a Dictionary<> safely?)

我需要在字典中添加键/对,但是我当然需要首先检查密钥是否已经存在,否则我得到一个“ 密码已经存在于字典 ”中。 下面的代码解决了这个,但是很笨重。

这样做一个更优雅的方式,而不需要像这样的字符串帮助方法?

using System; using System.Collections.Generic; namespace TestDictStringObject { class Program { static void Main(string[] args) { Dictionary<string, object> currentViews = new Dictionary<string, object>(); StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view1"); StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view2"); StringHelpers.SafeDictionaryAdd(currentViews, "Employees", "view1"); StringHelpers.SafeDictionaryAdd(currentViews, "Reports", "view1"); foreach (KeyValuePair<string, object> pair in currentViews) { Console.WriteLine("{0} {1}", pair.Key, pair.Value); } Console.ReadLine(); } } public static class StringHelpers { public static void SafeDictionaryAdd(Dictionary<string, object> dict, string key, object view) { if (!dict.ContainsKey(key)) { dict.Add(key, view); } else { dict[key] = view; } } } }

I need to add key/object pairs to a dictionary, but I of course need to first check if the key already exists otherwise I get a "key already exists in dictionary" error. The code below solves this but is clunky.

What is a more elegant way of doing this without making a string helper method like this?

using System; using System.Collections.Generic; namespace TestDictStringObject { class Program { static void Main(string[] args) { Dictionary<string, object> currentViews = new Dictionary<string, object>(); StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view1"); StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view2"); StringHelpers.SafeDictionaryAdd(currentViews, "Employees", "view1"); StringHelpers.SafeDictionaryAdd(currentViews, "Reports", "view1"); foreach (KeyValuePair<string, object> pair in currentViews) { Console.WriteLine("{0} {1}", pair.Key, pair.Value); } Console.ReadLine(); } } public static class StringHelpers { public static void SafeDictionaryAdd(Dictionary<string, object> dict, string key, object view) { if (!dict.ContainsKey(key)) { dict.Add(key, view); } else { dict[key] = view; } } } }

最满意答案

只需使用索引器 - 如果已经存在,它将覆盖,但不一定要先在其中:

Dictionary<string, object> currentViews = new Dictionary<string, object>(); currentViews["Customers"] = "view1"; currentViews["Customers"] = "view2"; currentViews["Employees"] = "view1"; currentViews["Reports"] = "view1";

如果键的存在表示一个错误(所以你想要它抛出)和索引器的基本上使用Add 。 (有点像铸造和使用之间的差异,参考转换。)

如果您使用C#3, 并且您有一个独特的键 ,您可以使这更加整洁:

var currentViews = new Dictionary<string, object>() { { "Customers", "view2" }, { "Employees", "view1" }, { "Reports", "view1" }, };

这在你的情况下不会奏效,因为集合初始化器总是使用Add将抛出第二个Customers条目。

Just use the indexer - it will overwrite if it's already there, but it doesn't have to be there first:

Dictionary<string, object> currentViews = new Dictionary<string, object>(); currentViews["Customers"] = "view1"; currentViews["Customers"] = "view2"; currentViews["Employees"] = "view1"; currentViews["Reports"] = "view1";

Basically use Add if the existence of the key indicates a bug (so you want it to throw) and the indexer otherwise. (It's a bit like the difference between casting and using as for reference conversions.)

If you're using C# 3 and you have a distinct set of keys, you can make this even neater:

var currentViews = new Dictionary<string, object>() { { "Customers", "view2" }, { "Employees", "view1" }, { "Reports", "view1" }, };

That won't work in your case though, as collection initializers always use Add which will throw on the second Customers entry.