0

Imagine that you have a dictionary like that:

Dictionary<int, int[]> dict = new Dictionary<int, int[]>();

So what I want to do is to ".add" to the value like a normal array.

I know I can add a Key and a Value like that:

dict.Add(0, new int[]{1, 2, 3, 4});

So I have this: Key=0, Value=[1, 2, 3, 4].

But what happen if I want to add a "5" at the value of the "Key=0" in order to make it appears like Key=0, Value=[1, 2, 3, 4, *5*]?

1
  • What you have to do is to extract the array and create a new one with the 5 at the end of it since Arrays have fixed size Commented Oct 13, 2018 at 17:16

1 Answer 1

2

To modify an an array inside a dictionary you could use LINQ's Append():

dict[0] = dict[0].Append(5).ToArray();

But you should not use arrays if you want to modify them. Use List<T> instead:

var dict = new Dictionary<int, List<int>>();

dict.Add(0, new List<int> {1,2,3,4});

Then you can call Append() on the list inside the dictionary:

dict[0].Append(5);
Sign up to request clarification or add additional context in comments.

1 Comment

Try dict[0].Add(5) given a List<int> inside a Dictionary 🙂

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.