miltonjbradley
miltonjbradley

Reputation: 601

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#

Upvotes: 9

Views: 59675

Answers (5)

svick
svick

Reputation: 244757

Another way to add the array (it's not a list) to the dictionary is to use collection initializer:

var wordDictionary = new Dictionary<string, string[]> { "IN", IN };

This is exactly the same as creating the dictionary in a normal way and then calling Add("IN", IN).

Upvotes: 0

rikitikitik
rikitikitik

Reputation: 2450

Do you really need to convert your array into a string? You could very well use string[] instead of List in your dictionary:

var wordDictionary = new Dictionary<string, string[]>();
wordDictionary.Add("IN", IN);

But if you really want to convert your string array to List:

var wordDictionary = new Dictionary<string, List<string>>();
wordDictionary.Add("IN", IN.ToList());

Upvotes: 0

Ry-
Ry-

Reputation: 224858

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"});

Upvotes: 18

Robert Harvey
Robert Harvey

Reputation: 180787

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);

Upvotes: 2

BrokenGlass
BrokenGlass

Reputation: 160852

You currently have a string array, not a list - so it should be:

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

Then you can just add items like:

wordDictionary.Add("IN" , IN);

Upvotes: 1

Related Questions