c# - List< > Dictionary< K,List< >> 内部 (C#)

标签 c# list dictionary

学生在这里。

正在处理当前的 C# 项目。我必须创建一个 List< Card > 的扑克牌,和一个 Dictionary< string,List< Card >>。

列表是独立创建的,字典包含卡片的集合。可以在集合中添加或删除卡片。

不过,我在将卡片添加到收藏夹时遇到了问题。我已经从用户输入中获得了列表的索引号,并试图根据索引简单地更新字典中的值。

抛出错误的行在这里。错误是 无法将类型“< filename.CardClass >”隐式转换为 System.Collections.Generic.List< filename.CardClass >'

我这辈子都搞不懂这意味着什么以及如何解决它..

_collections[input] = _cards[cardSelectionIndex];

这是我当前的代码块:

    public void AddToCollection()
    {
        PrintValuesCollections<string, List<Card>>(_collections);
        Console.WriteLine("Type in the name of the collection to add a card to:");
        string input = Console.ReadLine();

        bool found = _collections.ContainsKey(input);
        if (found)
        {
            Console.WriteLine("List of current cards to choose from:");

            for (int i = 0; i < _cards.Count; i++)
            {
                    Console.WriteLine("Index number:\r\n"+i+"Card Info:\r\n"+_cards[i]+"\n");
            }

            Console.WriteLine("Type in the index of the card from the list to add to the collection:");
            string cardSelection = Console.ReadLine();
            int cardSelectionIndex = 0;
            while (!int.TryParse(cardSelection, out cardSelectionIndex))
            {
                Console.Write("Please enter a number from the list above: ");
                input = Console.ReadLine();
            }

            _collections[input] = _cards[cardSelectionIndex];
            _cards.RemoveAt(cardSelectionIndex);
        }
        else
            Console.WriteLine("Collection name not found.");
    }

最佳答案

我假设 _collections类型是 Dictionary<string, List<Card>>_cardsList<Card>

所以这就是您要尝试做的:

//_collections[input] = _cards[cardSelectionIndex];
List<Card> a = _collections[input];
Card b = _cards[cardSelectionIndex];
a = b;

请注意 a 的类型和 b .这正确地给出了错误:“Cannot implicitly convert type '< filename.CardClass >' to System.Collections.Generic.List< filename.CardClass >'

您可能想要做的是向该列表中添加一张卡片

List<Card> a = _collections[input];
Card b = _cards[cardSelectionIndex];
a.Add(b);

或者只是

_collections[input].Add(_cards[cardSelectionIndex]);

关于c# - List< > Dictionary< K,List< >> 内部 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46145570/

相关文章:

java - removeFirstOccurrence 和删除之间的区别

python - 将字典列表转换为 pandas DataFrame

python - 如何计算字典中某个键的对象数量?

c# - 调用方法并绘制

javascript - 如何在 javascript 的 FormData 中追加对象?

c# - 保持线程空闲或杀死它们/重新启动它们?

algorithm - 根据距离在 map 上对位置进行分组

c# - 使用多个 JWT 承载身份验证

xml - 如何获取所有使用的命名空间的列表?

java - 在 Java 8 中向 TreeMap 中的键添加多个值