小编典典

有没有更优雅的方法可以安全地将项目添加到 Dictionary<> 中?

all

我需要将键/对象对添加到字典中,但我当然需要先检查键是否已经存在,否则我会收到“ 键已存在于字典中 ”错误。下面的代码解决了这个问题,但很笨拙。

在不制作这样的字符串辅助方法的情况下,有什么更优雅的方法呢?

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

阅读 87

收藏
2022-08-29

共1个答案

小编典典

只需使用索引器 - 如果它已经存在,它将覆盖,但它不必 首先 存在:

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

如果键的存在表明存在错误(因此您希望它抛出),则基本上使用Add,否则使用索引器。(这有点像 cast 和 using asfor
reference 转换之间的区别。)

如果您使用的是 C# 3 并且您有一组不同的 keys ,您可以使这更加整洁:

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

但是,这在您的情况下不起作用,因为集合初始化程序总是使用Add它将在第二个Customers条目上抛出。

2022-08-29