有没有添加到字典℃的项目更优雅的方式;>安全? [英] Is there a more elegant way of adding an item to a Dictionary<> safely?

查看:146
本文介绍了有没有添加到字典℃的项目更优雅的方式;>安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



什么是做这个而不做字符串辅助方法,这样更优雅的方式?

 使用系统; 
使用System.Collections.Generic;

命名空间TestDictStringObject
{
类节目
{
静态无效的主要(字串[] args)
{
字典<串,对象> currentViews =新词典<字符串对象>();

StringHelpers.SafeDictionaryAdd(currentViews,客户,视图1);
StringHelpers.SafeDictionaryAdd(currentViews,客户,视图2);
StringHelpers.SafeDictionaryAdd(currentViews,员工,视图1);
StringHelpers.SafeDictionaryAdd(currentViews,报告,视图1);

的foreach(KeyValuePair<字符串对象>对在currentViews)
{
Console.WriteLine({0} {1},pair.Key,pair.Value) ;
}
到Console.ReadLine();
}
}

公共静态类StringHelpers
{
公共静态无效SafeDictionaryAdd(词典<字符串对象>字典,串键,对象视图)
{
如果
{
dict.Add(键,查看)(dict.ContainsKey(密钥)!);
}
,否则
{
字典[关键] =视图。
}
}
}
}


解决方案

只需使用索引 - 如果它已经存在,它将覆盖,但它不会的有无的是那里第一次:

 词典<字符串对象> currentViews =新词典<字符串对象>(); 
currentViews [客户] =厂景;
currentViews [客户] =视图2;
currentViews [员工] =厂景;
currentViews [报告] =厂景;



基本上使用添加如果的存在键表示一个错误(所以你要扔它),在其它的索引器。 (这是一个有点像铸造和使用参考转换之间的区别。)



如果您在使用C#3的和你有一组不同的键的,你可以让这甚至更整洁:

  VAR currentViews =新词典<字符串对象>()
{
{客户,视图2},
{员工,视图1},
{报告,视图1},
};

这不会工作你的情况虽然,因为集合初始化,总是用添加将在第二客户抛出项。


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

解决方案

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.

这篇关于有没有添加到字典℃的项目更优雅的方式;&GT;安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆