字典用字符串作为值的列表 [英] Dictionary with list of strings as value
问题描述
我有一本字典在我的值是一个列表。
当我添加键,如果该键存在,我想另一个字符串添加到值(表)?
。如果该键不存在,那么我创建一个值的新表的新条目,如果键存在,那么我仅仅指刚值添加到列表值
前。
词典<字符串列表<串GT;> myDic =新词典<字符串列表<串GT;>();
myDic.Add(则newkey,添加到现有列表<串>和不能创造新)
要手动做到这一点,你需要这样的:
列表<字符串>现有;
如果{
=存在新的List<(myDic.TryGetValue(键,从现有的)!);串>();
myDic [关键] =存在;
}
//在这一点上,我们知道,现有指的是在
//字典的有关名单,这种或那种方式。
existing.Add(的ExtraValue);
不过,在很多情况下,LINQ可以让这个平凡的使用 ToLookup
。例如,考虑一个列表与LT;人>
要变身为姓到名字为姓一本字典。你可以使用:
VAR namesBySurname = people.ToLookup(人=> person.Surname,
的人= GT ; person.FirstName);
I have a dictionary where my value is a List. When I add keys, if the key exists I want to add another string to the value (List)? If the key doesn't exist then I create a new entry with a new list with a value, if the key exists then I jsut add a value to the List value ex.
Dictionary<string, List<string>> myDic = new Dictionary<string, List<string>>();
myDic.Add(newKey, add to existing list<strings> and not create new one)
To do this manually, you'd need something like:
List<string> existing;
if (!myDic.TryGetValue(key, out existing)) {
existing = new List<string>();
myDic[key] = existing;
}
// At this point we know that "existing" refers to the relevant list in the
// dictionary, one way or another.
existing.Add(extraValue);
However, in many cases LINQ can make this trivial using ToLookup
. For example, consider a List<Person>
which you want to transform into a dictionary of "surname" to "first names for that surname". You could use:
var namesBySurname = people.ToLookup(person => person.Surname,
person => person.FirstName);
这篇关于字典用字符串作为值的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!