Reputation: 15
I'm trying to implement a dictionary where value is a 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:
Thanks!
Upvotes: 0
Views: 584
Reputation: 1559
There is a mistake in your dictionary initialization code. You have written-
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> 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.
Upvotes: 0
Reputation: 20901
Yes, it is because you use bare int
value which cannot be converted into LinkedList
implicitly. Instead, you should instance a new object as new LinkedListNode<int>(100);
.
As you see its Value
property holds the value which is 100
.
Upvotes: 1