40

我有一本字典,其中我的值是一个列表。当我添加键时,如果键存在我想向值(列表)添加另一个字符串?如果键不存在,那么我创建一个带有值的新列表的新条目,如果键存在,那么我只需将值添加到列表值 ex。

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

5 回答 5

47

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

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);
于 2013-07-26T17:27:47.550 回答
20

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

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

}
于 2013-07-26T17:42:58.483 回答
5

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

Dictionary<string, List<string>> myDic = new Dictionary<string, List<string>>();
myDic.Add(newKey, new List<string>(existingList));
于 2016-11-10T21:39:39.010 回答
3

一个更简单的方法是:

var dictionary = list.GroupBy(it => it.Key).ToDictionary(dict => dict.Key, dict => dict.Select(item => item.value).ToList());
于 2020-08-20T06:08:12.603 回答
1

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

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());
    }
}
于 2021-08-02T09:54:59.527 回答