简体   繁体   English

在字典 C# 中使用 LinkedList? 以及如何实施它的操作?

[英]Using LinkedList in Dictionary C#? And how to implement it's operations?

I'm trying to implement a dictionary where value is a LinkedList.我正在尝试实现一个值为 LinkedList 的字典。 Below is a scenario:下面是一个场景:

public class TransactionTest
{
    private Dictionary<string, LinkedListNode<int>> stocks = new Dictionary<string, LinkedListNode<int>>();

    public TransactionTest()
    {
    }

    public void BuyTransaction(string ticker, int amount) {

        if (!stocks.ContainsKey(ticker))
        {

            LinkedList<int> linkedLists = new LinkedList<int>();
            stocks.Add(ticker, linkedLists.AddFirst(amount));
        }

        else if (stocks.ContainsKey(ticker)) {
            LinkedList<int> linkedLists = new LinkedList<int>();

            stocks[ticker] = linkedLists.AddLast(amount);
        }
            
    }

    public void toStringImpl() {
        Console.WriteLine(stocks.ToString());
    }
}

But I'm getting an error below:但是我在下面收到错误:

TransactionTest test = new TransactionTest();
test.BuyTransaction("AAPL", 100);

 System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.LinkedListNode`1[System.Int32]]

I'm not sure how to go about this - how can I do the following:我不确定如何 go 关于这个 - 我怎样才能做到以下几点:

  1. Create a new LinkedList for a new Key when it doesn't exist in the dictionary字典中不存在时,为新的Key创建一个新的LinkedList
  2. If key exists, add amount at it's values' LinkedList如果键存在,则在它的值的 LinkedList 中添加 amount

Thanks!谢谢!

Yes, it is because you use bare int value which cannot be converted into LinkedList implicitly.是的,这是因为您使用不能隐式转换为LinkedList的裸int值。 Instead, you should instance a new object as new LinkedListNode<int>(100);相反,您应该将 new object 实例化为new LinkedListNode<int>(100); . .

As you see its Value property holds the value which is 100 .如您所见,其Value属性的值为100

在此处输入图像描述

There is a mistake in your dictionary initialization code.您的字典初始化代码有误。 You have written- private Dictionary<string, LinkedListNode<int>> stocks = new Dictionary<string, LinkedListNode<int>>();你写了- private Dictionary<string, LinkedListNode<int>> stocks = new Dictionary<string, LinkedListNode<int>>();

you need to be using LinkedList<int> instead of LinkedListNode<int> and you can continue doing an operation like-您需要使用LinkedList<int>而不是LinkedListNode<int>并且您可以继续执行以下操作 -

LinkedList<int> linkedLists = new LinkedList<int>();
stocks.Add(ticker, linkedLists.AddFirst(amount));

which will add a LinkedList as a value to your dictionary as per your requirement.这将根据您的要求将 LinkedList 作为值添加到您的字典中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM