用预定义的键创建字典C# [英] Creating dictionaries with pre-defined keys C#

查看:178
本文介绍了用预定义的键创建字典C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种定义字典进行重用的方法。即。我可以创建字典对象,而不必使用我想要的值填充它。

I'm looking for a way to define a dictionary for reuse. ie. I can create the dictionary object without having to populate it with the values I want.

这里是我目前(注意代码未测试,只是例子)

Here is what I have currently (note code not tested, just example)

public Dictionary<string, string> NewEntryDictionary()
{
    Dictionary<string, string> dic = new Dictionary<string, string>();

    // populate key value pair
    foreach(string name in Enum.GetNames(typeof(Suits))
    {
        dic.Add(name, "");
    }

    return dic;
}

最终结果应该是一个具有预定义键的新字典对象
但是我想避免这样做。

The end result should be a new dictionary object with a predefined set of keys. But I want to avoid doing it this way.

推荐答案

您是否关心您编写的代码的数量或效率还不清楚,从效率的角度来看,这是很好的 - 它是O(N),但这很难避免如果你填写一个带有N个条目的字典。

It's not really clear whether you're concerned about the amount of code you've written, or the efficiency of it. From an efficiency perspective, it's fine - it's O(N), but that's hard to avoid if you're populating a dictionary with N entries.

使用LINQ可以让源代码缩短:

You can definitely make the source code shorter though, using LINQ:

public Dictionary<string, string> NewEntryDictionary()
{
    return Enum.GetNames(typeof(Suits)).ToDictionary(name => name, name => "");
}

艾菲当然,这只是更短的代码。

That won't be any more efficient, of course... it's just shorter code.

这篇关于用预定义的键创建字典C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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