相关疑难解决方法(0)

是否有更优雅的方式将项目安全地添加到Dictionary <>?

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

在没有像这样的字符串帮助方法的情况下,这样做更优雅的方法是什么?

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; …
Run Code Online (Sandbox Code Playgroud)

c# collections dictionary

130
推荐指数
5
解决办法
7万
查看次数

标签 统计

c# ×1

collections ×1

dictionary ×1