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?
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.
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");
Dictionary<int, string>[] matrix = new Dictionary<int, string>[2];
Doing this allocates the array 'matrix', but the the dictionaries supposed to be contained in that array are never instantiated. You have to create a Dictionary object in all cells in the array by using the new keyword.
matrix[0] = new Dictionary<int, string>();
matrix[0].Add(0, "first str");
You've initialized the array, but not the dictionary. You need to initialize matrix[0] (though that should cause a null reference exception).
You forgot to initialize the Dictionary. Just put the line below before adding the item:
matrix[0] = new Dictionary<int, string>();
Related
In Dictionary I can get a list of its Key/Values like in the below code:
Dictionary<string, string> dictionary = new Dictionary<string, string>();
List<string> list_of_first_elements = new List<string>();
list_of_first_elements = new List<string> (dictionary.Keys);
Is there an attribute/method can do same with List<Tuple> without looping over the list and add its first/second elements? Something like that:
List<Tuple<string, string>> list_of_tuples = new List<Tuple<string, string>>();
list_of_first_elements = """SomeCode""";
As #KlausGütter and #2kay mentioned I used LINQ to do that and its performance is nearly to looping over the List but it's certainly more clear, and here is the code:
list_of_first_elements = list_of_tuples.Select(_ => _.Item1).ToList();
I have a dictionary < string,object > which has a mapping of a string and a dictionary < string,int >. How do I add a key value pair in the inside dictionary < string ,int > ?
Dictionary <string,object> dict = new Dictionary <string,object>();
Dictionary <string,int> insideDict = new Dictionary <string,int>();
// ad some values in insideDict
dict.Add("blah",insideDict);
So now the dict has a dictionary mapped with a string.Now I want to separately add values to the insideDict.
I tried
dict["blah"].Add();
Where am I going wrong?
Do you mean something like this?
var collection = new Dictionary<string, Dictionary<string, int>>();
collection.Add("some key", new Dictionary<string, int>());
collection["some key"].Add("inner key", 0);
Something like below
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("1", new Dictionary<string, int>());
(OR) if you already have defined the inner dictionary then
Dictionary<string, object> dict = new Dictionary<string, object>();
Dictionary<string, int> innerdict = new Dictionary<string, int>();
dict.Add("1", innerdict); // added to outer dictionary
string key = "1";
((Dictionary<string, int>)dict[key]).Add("100", 100); // added to inner dictionary
Per your comment tried this but screwed up somewhere
You didn't got it cause of your below line where you forgot to cast the inner dictionary value to Dictionary<string, int> since your outer dictionary value is object. You should rather have your outer dictionary declared strongly typed.
dict.Add("blah",insideDict); //forgot casting here
Dictionary<string, Dictionary<string,TValue>> dic = new Dictionary<string, Dictionary<string,TValue>>();
Replace the TValue with your value type.
SortedList<int, string> months = new SortedList<int, string>();
SortedList<int, SortedList> all = new SortedList<int, SortedList>();
i want to create a SortedList which contains another sorted list of type of 'months' as in the above code snippet.
months.Add(1, "January");
all.Add(2012,months);
i get error
cannot convert from 'System.Collections.Generic.SortedList' to 'System.Collections.SortedList'
m confused...
You forgot to specify the type arguments for the inner SortedList, and it found a non-generic one, which is a different type. Do this:
var all = new SortedList<int, SortedList<int, string>>();
You'll have to name your parameters (otherwise it's a different type). Try this:
SortedList<int, SortedList<int, string> > all = new SortedList<int, SortedList<int, string> >();
I have a jagged dictionary:
Dictionary<string, Dictionary<int, Dictionary<string, string>>> tierOptions = new Dictionary<string, Dictionary<int, Dictionary<string, string>>>();
Later on, I have code that sets one of those values in the array:
tierOptions[optionID][npID]["tName"] = cboTier.Text;
The problem is that when it runs through this portion of code, all "tName" elements are set to cboTier.Text instead of just the one element.
For instance if optionID was 1 and npID was 8, and I had these three:
tierOptions[1][8]["tName"]
tierOptions[2][8]["tName"]
tierOptions[3][8]["tName"]
That particular line of code would set all three, instead of just tierOptions[1][8]["tName"]
Any idea why it is doing this? Thanks!
It sounds simply like you have used the same dictionary instance in several "dimensions" (your terminology). Since this is a reference, they are all shared (there is no automatic clone-into-isolated-copies here).
When filling the data, take care to use isolated dictionary instances when the data should be separate.
Yep, I would say the sae as Marc.
Please take a look at this example how you can retreive the vlaue from your type of Dictionary:
Dictionary<string, Dictionary<int, Dictionary<string, string>>> dic = new Dictionary<string, Dictionary<int, Dictionary<string, string>>>();
//add to 1st dic:
dic.Add("A", new Dictionary<int, Dictionary<string, string>>());
//add to 2nd dic:
dic["A"].Add(1, new Dictionary<string, string>());
//add to 3rd dic:
dic["A"][1].Add("a", "value 1");
//string KeyIn3rdDic = dic["A"][1].ToString();
string ValueIn3rdDic = dic["A"][1]["a"]; //result is "value 1";
My requirement is
Dictionary<outerString, Dictionary<innerString, List<SelectListItem>>>
When I try to get the value of the inner Dictionary using key(outerString), it gives an error saying "cannot apply indexing with type of expression...............".
I have tried this
Dictionary<outerString, Dictionary<innerString, List<SelectListItem>>> dict1 = new
Dictionary<outerString, Dictionary<innerString, List<SelectListItem>>>;
Dictionary<innerString, List<SelectListItem>> dict2 = dict1.values["outerString"];
Any quick help will be greatly appreciated.
Thx in advance.
I guess what you need is just:
Dictionary<innerString, List<SelectListItem>> dict = dict1["someKey"];
You just need to change the last line of your code snippet to (I assumed where you wrote inner string and outer string you must meant string):
var dict = dict1["someValue"];
Additionally, you could probably make your code much readable with the var keyword:
var dict1 = new Dictionary<string, Dictionary<string, List<SelectListItem>>>();
var dict = dict1["someValue"];
So outerString and innerString are types? Did you actually just want a nested dictionary string -> string -> List<SelectListItem> ? If not, you'll have to show us the definition of these types, and give the compiler some way to convert from the string you are trying to index with...
You were close:
Dictionary<outerString, Dictionary<innerString, List<SelectListItem>>> dict1 = new
Dictionary<outerString, Dictionary<innerString, List<SelectListItem>>>();
// Get inner dictionary whose key is "someValue"
Dictionary<innerString, List<SelectListItem>> dict = dict1["someValue"]
Did I misunderstand you? This works fine
Dictionary<string, Dictionary<string, List<string>>> list = new Dictionary<string, Dictionary<string, List<string>>>();
list.Add("test", new Dictionary<string, List<string>>());
Dictionary<string, List<string>> inner = list["test"];
or
var list = new Dictionary<string, Dictionary<string, List<string>>>();
list.Add("test", new Dictionary<string, List<string>>());
Dictionary<string, List<string>> inner = list["test"];
In
Dictionary<string, Dictionary<string, List<T>> dict1 =
new Dictionary<string, Dictionary<string, List<T>>();
you need
List<T> list12 = dict1["key1"]["key2"];
List<int> list1 = new List<int>();
list1.Add(1);
list1.Add(2);
Dictionary<string, List<int>> innerDict = new Dictionary<string, List<int>>();
innerDict.Add("inner", list1);
Dictionary<string, Dictionary<string, List<int>>> dict1 =
new Dictionary<string, Dictionary<string, List<int>>>();
dict1.Add("outer", innerDict);
List<int> list2 = dict1["outer"]["inner"];
How about you use an array of strings for a key, rather than trying to nest the dictionaries -
Dictionary<string[], List<string>> dict =
new Dictionary<string[],List<string>>();
string[] key = {"inner", "outer"};
List<string> vals = new List<string>();
dict.Add(key, vals);