Add an Array to a Dictionary in C# - 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#

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

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

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

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

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

Related

Extract KeyValuePair<string, string> from dictionary to another dictionary<string, string>

I'm new to a programming with c#. How to extract IEnumarable key value pair from dictionary that has type <string, IEnumarable<KeyValuePair<string, string>>> to another dictionary<string, string>? Preferebly using linq. Thank you in advance.
Obviously KvpValues dictionary has some values in it. It's just a pseudo code for present what i have.
Trying to do something like that:
Dictionary<string, IEnumarable<KeyValuePair<string, string>>> KvpValues = new Dictionary<string, IEnumarable<KeyValuePair<string, string>>>();
Dictionary<string,string> values = KvpValues.Values.ForEach(k=>k.Key, v=>v.Value);
It seems like what you want to do is flatten the Values from the original Dictionary into a new Dictionary. Assuming there will be no key conflicts, your code is close, you just need to convert your IEnumerable<IEnumerable<KeyValuePair>> into a IEnumerable<KeyValuePair> which is what Enumerable.SelectMany does for you:
Dictionary<string,string> values = KvpValues.Values.SelectMany(kvs => kvs).ToDictionary(k => k.Key, v => v.Value);

Initialize Nested Dictionaries in c#

I need to know how to access and initialize a series of Dictionaries containing other dictionaries.
For example, if I have
class Conv{
Dictionary<int, Dictionary<int, Dictionary<int, List<double>>>> valori;
}
And I want to initiate the parameter "valori" with random numbers, how can I do it?
I would do it like
valori[n1].Values[n2].Values[n3]
But after the first "Value", MVS gives me an error. Maybe I have to allocate the memory first? I learned a little bit of c++, but I'm still new to c#
Also let me know if I forgot something important in my question
You need to create the sub-dictionaries for each key before using them
var list = new List<double> {d};
var d1 = new Dictionary<int, List<double>> {{n3, list }};
var d2 = new Dictionary<int, Dictionary<int, List<double>>> {{n2, d1}};
valori[n1] = d2;
You can also write this short in one line:
valori[n1] = new Dictionary<int, Dictionary<int, List<double>>> {{n2, new Dictionary<int, List<double>> {{n3, new List<double> {d}}}}};
When all dictionaries are actually created you can access them normally:
var savedList = valori[n1][n2][n3];
Since this syntax is very clunky and it is easy to make a mistake (missing if a sub-dictionary exists, overriding data, etc), I'd strongly suggest changing the datastructure or at least hiding it in a dedicated class
Maybe i'm mistaken but I can't think of situation that you would need this kind of structure but nevertheless here's my help:
First of all you need to assign the variable or you will get the error :
"Use of unassign local variable".So the code will be like:
Dictionary<int, Dictionary<int, Dictionary<int, List<double>>>> valori=new
Dictionary<int, Dictionary<int, Dictionary<int, List<double>>>>();
Secondly you need to add some data to the dictionary in order to use it later so
you should do :
valori.Add(2, new Dictionary<int, Dictionary<int, List<double>>>());
valori.Add(3, new Dictionary<int, Dictionary<int, List<double>>>());
valori.Add(4, new Dictionary<int, Dictionary<int, List<double>>>());
"notice that keys are different"
And instead of new Dictionary<int, Dictionary<int, List<double>>>() you should
enter a value of that type.

Creating Dictionary<string, Dictionary<T, T[]>[]>

In C#, what is the syntax for instantiating and initializing a dictionary containing as values an array of dictionaries, those dictionaries themselves containing arrays as values?
For example, (I believe),
Dictionary<string, Dictionary<string, string[]>[]>?
Here's an example of what I'm trying to do:
private static readonly Dictionary<string, Dictionary<string, DirectoryInfo[]>[]> OrderTypeToFulfillmentDict = new Dictionary<string, Dictionary<string, DirectoryInfo[]>>()
{
{"Type1", new []
{
ProductsInfo.Type1FulfillmentNoSurfacesLocations,
ProductsInfo.Type2FulfillmentSurfacesLocations
}
}
}
where Type1Fulfillment..., and Type2Fulfillment... are already constructed as
Dictionary<string, DirectoryInfo[]>.
This throws the following compiler error:
"Cannot convert from System.Collections.Generic.Dictionary<string, System.IO.DirectoryInfo[]>[] to System.Collections.Generic.Dictionary<string, System.IO.DirectoryInfo[]>"
Edit: The problem was, as Lanorkin pointed out, that I was missing the final [] in the new Dictionary<string, Dictionary<string, DirectoryInfo[]>>(). Still, it goes without saying that this probably isn't something anyone should be trying to do in the first place.
What you've got looks correct, but what you're doing has a real code smell about it that's going to lead to some serious technical debt.
For starters, rather than having an inner Dictionary<string, string[]> model this in a class with methods appropriate to what you're trying to model. Otherwise anyone accessing this type isn't going to have a clue about what it's really modeling.
Something like this:
var dic = new Dictionary<string, Dictionary<int, int[]>[]>
{
{
"key1",
new[]
{
new Dictionary<int, int[]>
{
{1, new[] {1, 2, 3, 4}}
}
}}
};
Dictionary<string, Dictionary<string, string[]>[]> complexDictionary = new Dictionary<string, Dictionary<string, string[]>[]>();
or using the var keyword:
var complexDictionary = new Dictionary<string, Dictionary<string, string[]>[]>();
The following is perfectly valid
// array of dictionary
Dictionary<int, string[]>[] matrix = new Dictionary<int, string[]>[4];
//Dictionary of string and dictionary array
Dictionary<string, Dictionary<string, string[]>[]> dicOfArrays= new Dictionary<string, Dictionary<string, string[]>[]>();
private static readonly Dictionary<string, Dictionary<string, DirectoryInfo[]>>
OrderTypeToFulfillmentDict = new Dictionary<string, Dictionary<string, DirectoryInfo[]>>()
{
{"Type1", new []
{
ProductsInfo.Type1FulfillmentNoSurfacesLocations,
ProductsInfo.Type2FulfillmentSurfacesLocations
}
}
}
You have the wrong type in your variable definition. Remove the final "[]" as you don't want an array of dictionaries.

How to Pass dictionary as the value of another dictionary?

var for_cat_dict = new Dictionary<string, string>();
var category_Dict = new Dictionary<string,Dictionary<string,string>>();
for_cat_dict.Add(bean.getId(), bean.getId());
Now I want to add elements to the category_dict. So I tried..
category_Dict.Add(bean.getId(),[for_cat_dict]);
But it doesnt work... any solutions??
It's not really clear what you're trying to do, but
Category_Dict.Add(bean.getId(), for_cat_dict);
should at least compile. Whether it'll do what you want is another matter - it's not clear whether these are local variables, fields etc. (It also looks like you're not following .NET naming conventions in various ways...)
Dictionary<string, string> for_cat_dict = new Dictionary<string, string>();
Dictionary<string, Dictionary<string, string>> Category_Dict = new Dictionary<string, Dictionary<string, string>>();
Category_Dict.Add("somekey", for_cat_dict);

How to create an array with label and not integer

Suppose I have an array of strings like :
myArray["hello", "my", "name", "is", "marco"]
to access to this variable, I have to put an integer as index. So if I wanto to extract the third element I just do :
myArray[2]
Now, I'd like to use label instead of integer.
So for example somethings like :
myArray["canada"]="hello";
myArray["america"]="my";
myArray["brazil"]="name";
myArray["gosaldo"]="is";
myArray["italy"]="marco";
How can I do this on C#? Is it possible? Thanks
That's called an associative array, and C# doesn't support them directly. However, you can achieve exactly the same the effect with a Dictionary<TKey, TValue>. You can add values with the Add method (which will throw an exception if you try to add an already existing key), or with the indexer directly, as below (this will overwrite the existing value if you use the same key twice).
Dictionary<string, string> dict = new Dictionary<string, string>();
dict["canada"] = "hello";
dict["america"] = "my";
dict["brazil"] = "name";
dict["gosaldo"] = "is";
dict["italy"] = "marco";
C# has a Dictionary class (and interface) to deal with this sort of storage. For example:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("canada", "hello");
dict.Add("america", "my");
dict.Add("brazil", "name");
dict.Add("gosaldo", "is");
Here are the docs: http://msdn.microsoft.com/en-us/library/xfhwa508.aspx
With a Dictionary you will be able to set the "key" for each item as a string, and and give them string "values". For example:
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("canada", "hello");
You're looking for an associative array and I think this question is what you're looking for.

Categories