How to use nested dictionary in C#? - c#

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

Related

Linq on nested Dictionary

I have a dictionary of dictionary and I want to find a value from inner dictionary by Linq .
My code is:
private Dictionary<string, Dictionary<int, string>> SubCategoryDictionary = new Dictionary<string, Dictionary<int, string>>();
private Dictionary<int, string> BGA_Dictionary = new Dictionary<int, string>();
private Dictionary<int, string> Lead3D_Dictionary = new Dictionary<int, string>();
private Dictionary<int, string> Lead2D_Dictionary = new Dictionary<int, string>();
private Dictionary<int, string> Leadless_Dictionary = new Dictionary<int, string>();
private Dictionary<int, string> PIC_Dictionary = new Dictionary<int, string>();
In my constructor I have all values like this:--
BGA_Dictionary.Add(1, "Body_Measurement");
BGA_Dictionary.Add(2, "Ball_Measurement");
SubCategoryDictionary.Add("BGA", BGA_Dictionary);
Lead3D_Dictionary.Add(1, "Component_Height");
Lead3D_Dictionary.Add(2, "Rib_Measurement");
SubCategoryDictionary.Add("Package", Lead3D_Dictionary);
Lead2D_Dictionary.Add(1, "Dirt_Inspection");
Lead2D_Dictionary.Add(2, "Half_Cut_Inspection");
SubCategoryDictionary.Add("Mark", Lead2D_Dictionary);
Now I need a Lambda expression which will give me something like :
when key of SubCategoryDictionary ="Mark" and key of Lead3D_Dictionary =2 then I should get "Rib_Measurement".
I tried with following code :
string q = (from cls in SubCategoryDictionary
from s in cls.Value
where cls.Key == "Mark" && s.Key == 3
select s.Value).FirstOrDefault();
foreach (var a in q)
{
}
This above code works but I need in lambda expression. So if someone help me in formation of Lambda formation. It will be of great help.
Thanks.
I'm not sure why you ever need a lambda for accessing a dictionary by keys, but here it is:
Func<string,int,string> lambda = (k1, k2) => SubCategoryDictionary[k1][k2];
Now you can invoke it with var subCategory = lambda("Mark", 2);
I guess below code should get you the value you are trying to get.
var lead3 = SubCategoryDictionary["Mark"].SingleOrDefault(x => x.Key == 2).Value;
The idea is to use the Key of the first dictionary and get the value of it than filter it with SingleOrDefault method by providing a key to the inner dictionary value you are interested in.
Hope this helps

Adding a key value pair in a dictionary inside a dictionary

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.

How can I get the inner list value of list of keyvaluepair of (string, list)?

I am now struggling to find a way to get inner list from complicated List of keyvalupair.
public static List<KeyValuePair<string, List<KeyValuePair<int, string>>>> conditions = new List<KeyValuePair<string, List<KeyValuePair<int, string>>>>();
I want list from above list using given string value as a key.
Can anyone help me please?
You can use FirstOrDefault method like this:
conditions.FirstOrDefault(x => x.Key == "key").Value;
Or you should probably use a Dictionary instead.
You could use a Dictionary and a Dictionary as your value as well.
public static Dictionary<string, Dictionary<int, string>> conditions = new Dictionary<string, Dictionary<int, string>>();
and access it with conditions[key]
For example:
//Initialize random, pointless dictionary for example
var conditions = new Dictionary<string, Dictionary<int, string>>
{
{
"firstDict", new Dictionary<int, string>
{
{1, "blue"},
{2, "red"}
}
},
{
"secondDict", new Dictionary<int, string>
{
{1, "car"},
{2, "truck"}
}
}
};
//Get dictionary with key value "firstDict"
var firstDict = conditions["firstDict"];
//Gets the value associated with key "1"
var color = firstDict[1];

cannot create a SortedList having another SortedList

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

Array of dictionaries in C#

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

Categories

Resources