Y.V
Y.V

Reputation: 15

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

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:

  1. Create a new LinkedList for a new Key when it doesn't exist in the dictionary
  2. If key exists, add amount at it's values' LinkedList

Thanks!

Upvotes: 0

Views: 584

Answers (2)

akg179
akg179

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

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.

enter image description here

Upvotes: 1

Related Questions