c#字典如何为单个键添加多个值?
我已经创建了dictionary对象c#字典如何为单个键添加多个值?,c#,list,dictionary,C#,List,Dictionary,我已经创建了dictionary对象 Dictionary<string, List<string>> dictionary = new Dictionary<string,List<string>>(); 字典= 新字典(); 我想将字符串值添加到给定单个键的字符串列表中。 如果密钥不存在,那么我必须添加一个新密钥列表不是预定义的,我的意思是我没有创建任何列表对象,然后提供给字典。添加(“key”,Listname)。如何在字典中动态
Dictionary<string, List<string>> dictionary =
new Dictionary<string,List<string>>();
字典=
新字典();
我想将字符串值添加到给定单个键的字符串列表中。
如果密钥不存在,那么我必须添加一个新密钥<代码>列表不是预定义的,我的意思是我没有创建任何列表对象,然后提供给字典。添加(“key”,Listname)
。如何在字典中动态创建此列表对象。添加(“key”,Listname)
,然后将字符串添加到此列表。如果我必须添加100个键,那么我是否必须在执行dictionary.add
指令之前创建100个列表,以及我是否必须细化此列表的内容
多谢各位 更新:使用
TryGetValue
检查是否存在,以便在您有以下列表的情况下仅执行一次查找:
List<int> list;
if (!dictionary.TryGetValue("foo", out list))
{
list = new List<int>();
dictionary.Add("foo", list);
}
list.Add(2);
列表;
if(!dictionary.TryGetValue(“foo”,out list))
{
列表=新列表();
添加(“foo”,列表);
}
增加(2);
原件: 检查是否存在并添加一次,然后输入字典以获取列表并按正常方式添加到列表中:
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);
var dictionary=newdictionary();
如果(!dictionary.ContainsKey(“foo”))
添加(“foo”,newlist());
字典[“foo”]。添加(42);
字典[“foo”].AddRange(一百分之一);
或者像您的情况一样列出
另一方面,如果您知道要向动态集合(如列表
)添加多少项,请选择使用初始列表容量的构造函数:新列表(100)代码>
这将预先获取满足指定容量所需的内存,而不是在每次内存开始填满时获取小块内存。如果你知道你有100把钥匙,你也可以使用字典。如果我了解你想要什么:
dictionary.Add("key", new List<string>());
添加字符串时,请根据键是否已存在来执行不同的操作。要为键添加字符串值
,请执行以下操作:
List<string> list;
if (dictionary.ContainsKey(key)) {
list = dictionary[key];
} else {
list = new List<string>();
dictionary.Add(ley, list);
}
list.Add(value);
列表;
if(字典容器(键)){
列表=字典[键];
}否则{
列表=新列表();
字典。添加(ley,list);
}
列表。添加(值);
您可以使用我的multimap实现,它源自字典。它不是完美的,但是它做得很好
/// <summary>
/// Represents a collection of keys and values.
/// Multiple values can have the same key.
/// </summary>
/// <typeparam name="TKey">Type of the keys.</typeparam>
/// <typeparam name="TValue">Type of the values.</typeparam>
public class MultiMap<TKey, TValue> : Dictionary<TKey, List<TValue>>
{
public MultiMap()
: base()
{
}
public MultiMap(int capacity)
: base(capacity)
{
}
/// <summary>
/// Adds an element with the specified key and value into the MultiMap.
/// </summary>
/// <param name="key">The key of the element to add.</param>
/// <param name="value">The value of the element to add.</param>
public void Add(TKey key, TValue value)
{
List<TValue> valueList;
if (TryGetValue(key, out valueList)) {
valueList.Add(value);
} else {
valueList = new List<TValue>();
valueList.Add(value);
Add(key, valueList);
}
}
/// <summary>
/// Removes first occurence of an element with a specified key and value.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
/// <param name="value">The value of the element to remove.</param>
/// <returns>true if the an element is removed;
/// false if the key or the value were not found.</returns>
public bool Remove(TKey key, TValue value)
{
List<TValue> valueList;
if (TryGetValue(key, out valueList)) {
if (valueList.Remove(value)) {
if (valueList.Count == 0) {
Remove(key);
}
return true;
}
}
return false;
}
/// <summary>
/// Removes all occurences of elements with a specified key and value.
/// </summary>
/// <param name="key">The key of the elements to remove.</param>
/// <param name="value">The value of the elements to remove.</param>
/// <returns>Number of elements removed.</returns>
public int RemoveAll(TKey key, TValue value)
{
List<TValue> valueList;
int n = 0;
if (TryGetValue(key, out valueList)) {
while (valueList.Remove(value)) {
n++;
}
if (valueList.Count == 0) {
Remove(key);
}
}
return n;
}
/// <summary>
/// Gets the total number of values contained in the MultiMap.
/// </summary>
public int CountAll
{
get
{
int n = 0;
foreach (List<TValue> valueList in Values) {
n += valueList.Count;
}
return n;
}
}
/// <summary>
/// Determines whether the MultiMap contains an element with a specific
/// key / value pair.
/// </summary>
/// <param name="key">Key of the element to search for.</param>
/// <param name="value">Value of the element to search for.</param>
/// <returns>true if the element was found; otherwise false.</returns>
public bool Contains(TKey key, TValue value)
{
List<TValue> valueList;
if (TryGetValue(key, out valueList)) {
return valueList.Contains(value);
}
return false;
}
/// <summary>
/// Determines whether the MultiMap contains an element with a specific value.
/// </summary>
/// <param name="value">Value of the element to search for.</param>
/// <returns>true if the element was found; otherwise false.</returns>
public bool Contains(TValue value)
{
foreach (List<TValue> valueList in Values) {
if (valueList.Contains(value)) {
return true;
}
}
return false;
}
}
//
///表示键和值的集合。
///多个值可以具有相同的键。
///
///钥匙的类型。
///值的类型。
公共类多重映射:字典
{
公共多重映射()
:base()
{
}
公共多地图(国际容量)
:基本(容量)
{
}
///
///将具有指定键和值的元素添加到多重映射中。
///
///要添加的元素的键。
///要添加的元素的值。
公共无效添加(TKey键,TValue值)
{
价值清单;
if(TryGetValue(键,输出值列表)){
价值清单。添加(价值);
}否则{
valueList=新列表();
价值清单。添加(价值);
添加(键、值列表);
}
}
///
///删除具有指定键和值的元素的第一次出现。
///
///要删除的元素的键。
///要删除的元素的值。
///如果删除了某个元素,则为true;
///如果未找到键或值,则为false。
公共bool Remove(TKey键,TValue值)
{
价值清单;
if(TryGetValue(键,输出值列表)){
如果(值列表。删除(值)){
如果(valueList.Count==0){
取下(钥匙);
}
返回true;
}
}
返回false;
}
///
///删除具有指定键和值的所有元素。
///
///要删除的元素的键。
///要删除的元素的值。
///删除的元素数。
public int RemoveAll(TKey键,TValue值)
{
价值清单;
int n=0;
if(TryGetValue(键,输出值列表)){
while(值列表.删除(值)){
n++;
}
如果(valueList.Count==0){
取下(钥匙);
}
}
返回n;
}
///
///获取多重映射中包含的值的总数。
///
公共整数计数
{
得到
{
int n=0;
foreach(在值中列出值列表){
n+=valueList.Count;
}
返回n;
}
}
///
///确定多重映射是否包含具有特定属性的元素
///键/值对。
///
///要搜索的元素的键。
///要搜索的元素的值。
///如果找到元素,则为true;否则为false。
公共bool包含(TKey键、TValue值)
{
价值清单;
if(TryGetValue(键,输出值列表)){
返回值列表。包含(值);
}
返回false;
}
///
///确定多重贴图是否包含具有特定值的元素。
///
///要搜索的元素的值。
///如果找到元素,则为true;否则为false。
公共布尔包含(TValue值)
{
foreach(在值中列出值列表){
if(值列表包含(值)){
返回true;
}
}
返回false;
}
}
请注意,Add
方法查看是否已经存在一个键。如果键是新的,则会创建一个新列表,将值添加到列表中,并将列表添加到字典中。如果键已存在,则新值将添加到现有列表中。Dictionary Dictionary=new Dictionary();
Dictionary<string, List<string>> dictionary = new Dictionary<string,List<string>>();
foreach(string key in keys) {
if(!dictionary.ContainsKey(key)) {
//add
dictionary.Add(key, new List<string>());
}
dictionary[key].Add("theString");
}
foreach(字符串键入键){
如果(!dictionary.ContainsKey(键)){
//加
添加(键,新列表());
}
辞典
Dictionary<string, List<string>> dictionary = new Dictionary<string,List<string>>();
foreach(string key in keys) {
if(!dictionary.ContainsKey(key)) {
//add
dictionary.Add(key, new List<string>());
}
dictionary[key].Add("theString");
}
void Add(string key, string val)
{
List<string> list;
if (!dictionary.TryGetValue(someKey, out list))
{
values = new List<string>();
dictionary.Add(key, list);
}
list.Add(val);
}
var myData = new[]{new {a=1,b="frog"}, new {a=1,b="cat"}, new {a=2,b="giraffe"}};
ILookup<int,string> lookup = myData.ToLookup(x => x.a, x => x.b);
IEnumerable<string> allOnes = lookup[1]; //enumerable of 2 items, frog and cat
System.Collections.Specialized.NameValueCollection myCollection
= new System.Collections.Specialized.NameValueCollection();
myCollection.Add(“Arcane”, “http://arcanecode.com”);
myCollection.Add(“PWOP”, “http://dotnetrocks.com”);
myCollection.Add(“PWOP”, “http://dnrtv.com”);
myCollection.Add(“PWOP”, “http://www.hanselminutes.com”);
myCollection.Add(“TWIT”, “http://www.twit.tv”);
myCollection.Add(“TWIT”, “http://www.twit.tv/SN”);
public static void AddToList<T, U>(this IDictionary<T, List<U>> dict, T key, U elementToList)
{
List<U> list;
bool exists = dict.TryGetValue(key, out list);
if (exists)
{
dict[key].Add(elementToList);
}
else
{
dict[key] = new List<U>();
dict[key].Add(elementToList);
}
}
Dictionary<int, List<string>> dict = new Dictionary<int, List<string>>();
dict.AddToList(4, "test1");
dict.AddToList(4, "test2");
dict.AddToList(4, "test3");
dict.AddToList(5, "test4");
MultiDictionary<string, int> myDictionary = new MultiDictionary<string, int>();
myDictionary.Add("key", 1);
myDictionary.Add("key", 2);
myDictionary.Add("key", 3);
//myDictionary["key"] now contains the values 1, 2, and 3
Dictionary<string,List<string>> NewParent = new Dictionary<string,List<string>>();
child = new List<string> ();
child.Add('SomeData');
NewParent["item1"].AddRange(child);
using System.Linq;
using System.Collections.Generic;
using System.Collections.Concurrent;
...
var dictionary = new ConcurrentDictionary<string, IEnumerable<string>>();
var itemToAdd = "item to add to key-list";
dictionary.AddOrUpdate("key", new[]{itemToAdd}, (key,list) => list.Append(itemToAdd));
// If "key" doesn't exist, creates it with a list containing itemToAdd as value
// If "key" exists, adds item to already existent list (third parameter)