C#字典如何为单个键添加多个值? [英] c# dictionary How to add multiple values for single key?

查看:5051
本文介绍了C#字典如何为单个键添加多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建字典对象

Dictionary<string, List<string>> dictionary =
    new Dictionary<string,List<string>>();



我要的字符串值添加到字符串列表对于给定的一个键。
如果密钥已经不存在,那么我要补充一个新的密钥。 列表<串> 不是预定义的,我的意思是我没有创建任何列表对象,然后提供给 dictionary.Add(钥匙,列表名)。如何创建动态的此列表对象dictionary.Add(密钥,列表名),然后添加字符串到这个列表。如果非要加100键然后我必须执行 dictionary.Add 指令之前创造100名单也做我必须pedefine这个列表的内容?

I want to add string values to the list of string for a given single key. If the key doesn't already exists then I have to add a new key. List<string> is not predefined, I mean I didn't create any list object and then supplied to dictionary.Add("key",Listname). How to create dynamically this list object in dictionary.Add("key",Listname) and then add strings to this list. If I have to add 100 keys then do I have to create 100 lists before executing dictionary.Add instruction and also do I have to pedefine the contents of this lists ?

感谢您。

推荐答案

更新:检查使用存在 TryGetValue 只做一个查找的情况下,你有名单:

Update: check for existence using TryGetValue to do only one lookup in the case where you have the list:

List<int> list;

if (!dictionary.TryGetValue("foo", out list))
{
    list = new List<int>();
    dictionary.Add("foo", list);
}

list.Add(2);





原文:
检查存在,并添加一次,然后钥匙插入字典来获取列表和添加到列表正常:


Original: Check for existence and add once, then key into the dictionary to get the list and add to the list as normal:

var dictionary = new Dictionary<string, List<int>>();

if (!dictionary.ContainsKey("foo"))
    dictionary.Add("foo", new List<int>());

dictionary["foo"].Add(42);
dictionary["foo"].AddRange(oneHundredInts);

列表<串> 作为你案例

顺便说一句,如果你知道你要多少项目添加到动态集合,如列表< T> ,青睐,是以初始列表容量的构造:新的List< INT>(100);

As an aside, if you know how many items you are going to add to a dynamic collection such as List<T>, favour the constructor that takes the initial list capacity: new List<int>(100);.

这将抢来满足指定的容量所需内存的前期的,而不是每次开始填充时间抓住小块。如果你知道你有100个键,你可以做同样的字典。

This will grab the memory required to satisfy the specified capacity upfront, instead of grabbing small chunks every time it starts to fill up. You can do the same with dictionaries if you know you have 100 keys.

这篇关于C#字典如何为单个键添加多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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