Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an Array to a Dictionary in C#

I have tried reading the other posts on this subject and can't quite figure this out.

I have a list in C# that I want to put in a dictionary with all of the same keys. The list is this

string[] IN ={"Against","Like","Upon","Through","Of","With","Upon","On","Into","From","by","that","In","About","For"
    ,"Along","Before","Beneath","At","Across","beside","After","Though","Among","Toward","If"};

I want to create and populate a dictionary with the key being "IN" (the name of the array) and then having each string for the array in the dictionary.

This is what I wrote to create the dictionary (which I am not sure is correct):

Dictionary<string, List<string>> wordDictionary = new Dictionary<string, List<string>> ()

But I am not sure how to populate the dictionary.

Any help would be greatly appreciated as this is the first time I have tried to use a dictionary and I am new to C#

like image 919
miltonjbradley Avatar asked Mar 02 '12 01:03

miltonjbradley


Video Answer


2 Answers

An array is string[], not List<string>, so just do this:

Dictionary<string, string[]> wordDictionary = new Dictionary<string, string[]>();

Now you can add your array as usual.

wordDictionary.Add("IN", IN);

Or:

wordDictionary.Add("IN", new string[] {"Against","Like","Upon","Through","Of","With","Upon","On","Into","From","by","that","In","About","For","Along","Before","Beneath","At","Across","beside","After","Though","Among","Toward","If"});
like image 152
Ry- Avatar answered Oct 06 '22 00:10

Ry-


Dictionary.Add("IN", new List<string>(IN));

...if you want to keep the current signature for your dictionary.

If you change it to Dictionary<string, string[]> then you can just:

Dictionary.Add("IN",IN);
like image 40
Robert Harvey Avatar answered Oct 05 '22 23:10

Robert Harvey