字典与字符串列表作为值

use*_*050 26 c# dictionary list

我有一个字典,我的值是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)
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 35

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

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);
Run Code Online (Sandbox Code Playgroud)

但是,在许多情况下,LINQ可以使用这个简单的方法ToLookup.例如,考虑一个List<Person>你想要转换成"姓氏"字典为"姓氏的名字"的字典.你可以使用:

var namesBySurname = people.ToLookup(person => person.Surname,
                                     person => person.FirstName);
Run Code Online (Sandbox Code Playgroud)

  • @BKSpurgeon:您总是可以将鼠标悬停在var上以查看确切的类型。在这种情况下,它将是ILookup &lt;string,string&gt;。 (2认同)

sar*_*ris 13

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

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

}
Run Code Online (Sandbox Code Playgroud)

  • 我认为没有任何迹象表明"价值表"仅包含唯一值. (2认同)
  • 有*很多*的情况是合适的。想象一下购物系统中的一个案例,它对“按订单 ID 的订单项”进行分组 - 您想区分“这个订单是一个汉堡”和“这个订单是五个汉堡”之间的区别。特别是,据我所知,您悄悄添加了问题中未提及的*任何*方式的行为。 (2认同)

Chr*_*ler 7

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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());
    }
}
Run Code Online (Sandbox Code Playgroud)


Gab*_*scu 6

一种更简单的方法是:

var dictionary = list.GroupBy(it => it.Key).ToDictionary(dict => dict.Key, dict => dict.Select(item => item.value).ToList());
Run Code Online (Sandbox Code Playgroud)


小智 5

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

Dictionary<string, List<string>> myDic = new Dictionary<string, List<string>>();
myDic.Add(newKey, new List<string>(existingList));
Run Code Online (Sandbox Code Playgroud)