c#dictionary如何为单个键添加多个值?
我创建了字典对象
Dictionary<string, List> dictionary = new Dictionary<string,List>();
我想将字符串值添加到给定单个键的字符串列表中。 如果密钥尚不存在,那么我必须添加一个新密钥。 List
不是预定义的,我的意思是我没有创建任何列表对象,然后提供给dictionary.Add("key",Listname)
。 如何在dictionary.Add("key",Listname)
动态创建此列表对象,然后将字符串添加到此列表中。 如果我必须添加100个密钥,那么在执行dictionary.Add
指令之前我是否必须创建100个列表,并且还必须pedefine此列表的内容?
谢谢。
更新:使用TryGetValue
检查是否存在,只有在您拥有列表的情况下才执行一次查找:
List list; if (!dictionary.TryGetValue("foo", out list)) { list = new List (); dictionary.Add("foo", list); } list.Add(2);
原始:检查是否存在并添加一次,然后键入字典以获取列表并正常添加到列表中:
var dictionary = new Dictionary>(); if (!dictionary.ContainsKey("foo")) dictionary.Add("foo", new List()); dictionary["foo"].Add(42); dictionary["foo"].AddRange(oneHundredInts);
或者像您的情况一样List
。
顺便说一句,如果您知道要将多少项添加到动态集合(例如List
,请使用获取初始列表容量的构造函数: new List
。
这将占用预先满足指定容量所需的内存,而不是每次开始填满时抓取小块。 如果您知道有100个键,则可以对词典执行相同操作。
如果我理解你想要的东西:
dictionary.Add("key", new List());
后来…
dictionary["key"].Add("string to your list");
Dictionary> dictionary = new Dictionary>(); foreach(string key in keys) { if(!dictionary.ContainsKey(key)) { //add dictionary.Add(key, new List ()); } dictionary[key].Add("theString"); }
如果密钥不存在,则添加新的List
(在if中)。 否则密钥存在,所以只需在该密钥下的List
添加一个新值即可。
你可以使用我的多图的实现,它来自Dictionary
。 它并不完美,但它做得很好。
/// /// Represents a collection of keys and values. /// Multiple values can have the same key. /// /// Type of the keys. /// Type of the values. public class MultiMap : Dictionary> { public MultiMap() : base() { } public MultiMap(int capacity) : base(capacity) { } /// /// Adds an element with the specified key and value into the MultiMap. /// /// The key of the element to add. /// The value of the element to add. public void Add(TKey key, TValue value) { List valueList; if (TryGetValue(key, out valueList)) { valueList.Add(value); } else { valueList = new List (); valueList.Add(value); Add(key, valueList); } } /// /// Removes first occurence of an element with a specified key and value. /// /// The key of the element to remove. /// The value of the element to remove. /// true if the an element is removed; /// false if the key or the value were not found. public bool Remove(TKey key, TValue value) { List valueList; if (TryGetValue(key, out valueList)) { if (valueList.Remove(value)) { if (valueList.Count == 0) { Remove(key); } return true; } } return false; } /// /// Removes all occurences of elements with a specified key and value. /// /// The key of the elements to remove. /// The value of the elements to remove. /// Number of elements removed. public int RemoveAll(TKey key, TValue value) { List valueList; int n = 0; if (TryGetValue(key, out valueList)) { while (valueList.Remove(value)) { n++; } if (valueList.Count == 0) { Remove(key); } } return n; } /// /// Gets the total number of values contained in the MultiMap. /// public int CountAll { get { int n = 0; foreach (List valueList in Values) { n += valueList.Count; } return n; } } /// /// Determines whether the MultiMap contains an element with a specific /// key / value pair. /// /// Key of the element to search for. /// Value of the element to search for. /// true if the element was found; otherwise false. public bool Contains(TKey key, TValue value) { List valueList; if (TryGetValue(key, out valueList)) { return valueList.Contains(value); } return false; } /// /// Determines whether the MultiMap contains an element with a specific value. /// /// Value of the element to search for. /// true if the element was found; otherwise false. public bool Contains(TValue value) { foreach (List valueList in Values) { if (valueList.Contains(value)) { return true; } } return false; } }
请注意, Add
方法查看是否已存在密钥。 如果密钥是新的,则创建新列表,将值添加到列表中,并将列表添加到字典中。 如果密钥已存在,则新值将添加到现有列表中。
尽管与大多数其他响应几乎相同,但我认为这是实现它的最有效和最简洁的方法。 使用TryGetValue比使用ContainsKey并重新索引到字典中更快,正如其他一些解决方案所示。
void Add(string key, string val) { List list; if (!dictionary.TryGetValue(someKey, out list)) { values = new List (); dictionary.Add(key, list); } list.Add(val); }
使用NameValuedCollection。
好的起点就在这里 。 直接从链接。
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”);
添加字符串时,请根据密钥是否已存在而采用不同的方式。 要为密钥添加字符串value
:
List list; if (dictionary.ContainsKey(key)) { list = dictionary[key]; } else { list = new List (); dictionary.Add(ley, list); } list.Add(value);
而不是使用字典,为什么不转换为ILookup?
var myData = new[]{new {a=1,b="frog"}, new {a=1,b="cat"}, new {a=2,b="giraffe"}}; ILookup lookup = myData.ToLookup(x => xa, x => xb); IEnumerable allOnes = lookup[1]; //enumerable of 2 items, frog and cat
ILookup是一种不可变的数据结构,允许每个键有多个值。 如果您需要在不同时间添加项目,可能没什么用处,但如果您预先拥有所有数据,这绝对是可行的方法。
这里有一个答案的很多变化:)我是另一个,它使用扩展机制作为舒适的执行方式(方便):
public static void AddToList(this IDictionary> dict, T key, U elementToList) { List list; bool exists = dict.TryGetValue(key, out list); if (exists) { dict[key].Add(elementToList); } else { dict[key] = new List(); dict[key].Add(elementToList); } }
然后你按如下方式使用它:
Dictionary> dict = new Dictionary>(); dict.AddToList(4, "test1"); dict.AddToList(4, "test2"); dict.AddToList(4, "test3"); dict.AddToList(5, "test4");
有一个NuGet包Microsoft实验集 ,它包含一个MultiValueDictionary
类,它可以完全满足您的需求。
这是包的创建者的博客文章,进一步描述了它。
如果你感到好奇, 这是另一篇博客文章。
用法示例:
MultiDictionary myDictionary = new MultiDictionary(); myDictionary.Add("key", 1); myDictionary.Add("key", 2); myDictionary.Add("key", 3); //myDictionary["key"] now contains the values 1, 2, and 3
我试图将List添加到字典中的现有密钥并达到以下解决方案:
Dictionary> NewParent = new Dictionary>(); child = new List (); child.Add('SomeData'); NewParent["item1"].AddRange(child);
它不会显示任何exception,也不会替换以前的值。