字典与字符串列表作为值
我有一个字典,我的值是List。 当我添加密钥时,如果密钥存在,我想在值(List)中添加另一个字符串? 如果密钥不存在,那么我创建一个带有值的新列表的新条目,如果密钥存在,那么我将jsut添加到List值ex的值。
Dictionary<string, List> myDic = new Dictionary<string, List>(); myDic.Add(newKey, add to existing list and not create new one)
要手动执行此操作,您需要以下内容:
List existing; if (!myDic.TryGetValue(key, out existing)) { existing = new List (); 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);
但是,在许多情况下,LINQ可以使用ToLookup
来实现这一点。 例如,考虑一个List
,它要将“surname”字典转换为“姓氏的名字”。 你可以使用:
var namesBySurname = people.ToLookup(person => person.Surname, person => person.FirstName);
我将字典包装在另一个类中:
public class MyListDictionary { private Dictionary> internalDictionary = new Dictionary>(); public void Add(string key, string value) { if (this.internalDictionary.ContainsKey(key)) { List list = this.internalDictionary[key]; if (list.Contains(value) == false) { list.Add(value); } } else { List list = new List (); list.Add(value); this.internalDictionary.Add(key, list); } } }
只需在字典中创建一个新数组
Dictionary> myDic = new Dictionary>(); myDic.Add(newKey, new List (existingList));