簡體   English   中英

字典與字符串列表作為值

[英]Dictionary with list of strings as value

我有一個字典,我的值是List。 當我添加密鑰時,如果密鑰存在,我想在值(List)中添加另一個字符串? 如果密鑰不存在,那么我創建一個帶有值的新列表的新條目,如果密鑰存在,那么我將jsut添加到List值ex的值。

Dictionary<string, List<string>> myDic = new Dictionary<string, List<string>>();
myDic.Add(newKey, add to existing list<strings> and not create new one)

要手動執行此操作,您需要以下內容:

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);

但是,在許多情況下,LINQ可以使用ToLookup來實現這一點。 例如,考慮一個List<Person> ,它要轉換為“surname”字典到“姓氏的名字”。 你可以使用:

var namesBySurname = people.ToLookup(person => person.Surname,
                                     person => person.FirstName);

我將字典包裝在另一個類中:

public class MyListDictionary
{

    private Dictionary<string, List<string>> internalDictionary = new Dictionary<string,List<string>>();

    public void Add(string key, string value)
    {
        if (this.internalDictionary.ContainsKey(key))
        {
            List<string> list = this.internalDictionary[key];
            if (list.Contains(value) == false)
            {
                list.Add(value);
            }
        }
        else
        {
            List<string> list = new List<string>();
            list.Add(value);
            this.internalDictionary.Add(key, list);
        }
    }

}

只需在字典中創建一個新數組

Dictionary<string, List<string>> myDic = new Dictionary<string, List<string>>();
myDic.Add(newKey, new List<string>(existingList));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM