Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of dictionaries in C#

Tags:

I would like to use something like this:

Dictionary<int, string>[] matrix = new Dictionary<int, string>[2]; 

But, when I do:

matrix[0].Add(0, "first str"); 

It throws " 'TargetInvocationException '...Exception has been thrown by the target of an invocation."

What is the problem? Am I using that array of dictionaries correctly?

like image 987
hradecek Avatar asked Feb 15 '12 20:02

hradecek


People also ask

Are Dictionaries an array?

Dictionaries are Python's implementation of a data structure that is more generally known as an associative array. A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value.

How do you define an array of objects in Objective C?

An array is an object that contains collections of other objects. Array objects in Objective-C are handled using the Foundation Framework NSArray class. The NSArray class contains a number of methods specifically designed to ease the creation and manipulation of arrays within Objective-C programs.

What is faster dictionary or array?

If you are going to get elements by positions (index) in the array then array will be quicker (or at least not slower than dictionary). If you are going to search for elements in the array than dictionary will be faster.


2 Answers

Try this:

Dictionary<int, string>[] matrix = new Dictionary<int, string>[]  {     new Dictionary<int, string>(),     new Dictionary<int, string>() }; 

You need to instantiate the dictionaries inside the array before you can use them.

like image 88
Andrew Hare Avatar answered Oct 08 '22 09:10

Andrew Hare


Did you set the array objects to instances of Dictionary?

Dictionary<int, string>[] matrix = new Dictionary<int, string>[2]; matrix[0] = new Dictionary<int, string>(); matrix[1] = new Dictionary<int, string>(); matrix[0].Add(0, "first str"); 
like image 26
ken Avatar answered Oct 08 '22 09:10

ken