[英]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 关于这个 - 我怎样才能做到以下几点:
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.