字典与字符串列表作为值

时间:2013-07-26 17:24:57

标签: c# list dictionary

我有一个字典,我的值是List。 当我添加密钥时,如果密钥存在,我想在值(List)中添加另一个字符串? 如果密钥不存在,那么我创建一个带有值的新列表的新条目,如果密钥存在则我将jsut添加到List值的值 离。

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

5 个答案:

答案 0 :(得分:34)

要手动执行此操作,您需要以下内容:

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>转换为“姓氏”字典转换为“姓氏的名字”。你可以使用:

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

答案 1 :(得分:10)

我将字典包装在另一个类中:

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

}

答案 2 :(得分:3)

只需在字典中创建一个新数组

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

答案 3 :(得分:1)

更简单的方法是:

var dictionary = list.GroupBy(it => it.Key).ToDictionary(dict => dict.Key, dict => dict.Select(item => item.value).ToList());

答案 4 :(得分:0)

我为此写了一个字典扩展:

public static class DictionaryExtensions
{
    public static void AddOrUpdate(this Dictionary<string, List<string>> targetDictionary, string key, string entry)
    {
        if (!targetDictionary.ContainsKey(key))
            targetDictionary.Add(key, new List<string>());

        targetDictionary[key].Add(entry);
    }
}

现在您可以简单地添加或更新:

using System;
using System.Collections.Generic;
using DictionaryExtensions;

public class Program
{
    public static void Main()
    {
        var newDic = new Dictionary<string, List<string>>();
        newDic.AddOrUpdate("Alpha","Anton");
        newDic.AddOrUpdate("Alpha","Boris");
        newDic.AddOrUpdate("Beta","Doris");
        newDic.AddOrUpdate("Delta","Emil");
        newDic.AddOrUpdate("Alpha","Ceasar");
        
        System.Console.Write(newDic["Alpha"][1].ToString());
    }
}