Adding a key value pair in a dictionary inside a dictionary - c#

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.

Related

Is it possible to store a KeyValuePair of a dictionary without the use of a foreach loop?

The syntax for iterating over a dictionary with a foreach loop is:
foreach (KeyValuePair<key, value> item in dictionary)
Inside the foreach loop the key is accessed with item.key and the value with item.value.
This got me thinking, can this be used without the use of a foreach loop as a convenient (although niche) way to represent a specific dictionary pair?
I am not looking for some weird work arounds, like running a foreach loop and saving the KeyValuePair into a variable once the target key is reached, because at this point it would be more convenient to just use 2 variables.
Like this
var dic = new Dictionary<string, int>();
dic["a"] = 42;
KeyValuePair<string, int> keyVal;
foreach(var kv in dic) {
keyVal = kv; << gets the last entry from the dictioanry
}
Note that the dictionary does not store KeyValuePairs, it creates one for the enumeration, so the simple thing to do is this (because we are not expensively recreating something)
var dic = new Dictionary<string, int>();
dic["a"] = 42;
KeyValuePair<string, int> keyVal = new KeyValuePair<string, int>("a", dic["a"]);
this is more efficient than the (neat) LINQ Sinlge method
The IDictionary<TKey, TValue> interface implements IEnumerable<KeyValuePair<TKey,TValue>>. This means you can simply use Single() to get the entry you want.
IDictionary<string, int> dict = ...;
KeyValuePair<string, int> entry = dict.Single(it => it.Key == "yourKey");
try this
var dict = new Dictionary<string, string>() {
{"hi","Hello World!"},
{"adieu","Goodby"}
};
string hi = dict["hi"]; //Hello World!
or if you want a list
List<KeyValuePair<string,string>> list = dict.ToList();
result
[{"Key":"hi","Value":"Hello World!"},{"Key":"adieu","Value":"Goodby"}]

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

How to search in a dictionary?

I am trying to search in a dictionary.
I have 2 dictionaries:
Dictionary<int, string> dict = new Dictionary<int, string>()
Dictionary<int, int> temp = new Dictionary<int, int>()
then ive populated this dictionary with:
dict.Add(123, "");
dict.Add(124, ""); //and so on
then i want to loop though this dictionary and recall the key and add that to the other dictionary
for (int i = 0; i < dict.Count; i++)
{
if (dict[i] == "")
{
temp.Add(dict[dict.ElementAt(i).Key],0);
dict[dict.ElementAt(i).Value] = "Moved";
}
}
i shall be doing other things inside this forloop so i cannot change that to a foreach loop. I am trying to check if the value of the Dictionary dict is empty then take the Key and copy the key value to the temp dictionary, but i am getting errors.
Please help :)
the problem im trying to solve is that i want to be able to search the dict dictionary for for a value with "" and take the key and store it in another dictionary temp (which will later on hold a second value). i need to do this in a for-loop as i want to be able to go back by changing the value of i.
i want to be able to use i to select both the key and value from the dict dictionary.
The errors i was getting was simply converting from string to int, i cannot get it to even store the key from dict into an int variable.
You need to put a value in the temp dictionary. I chose 0.
Dictionary<int, string> dict = new Dictionary<int, string>();
Dictionary<int, int> temp = new Dictionary<int, int>();
dict.Add(123, "");
dict.Add(124, ""); //and so on
int[] keys = dict.Keys.ToArray();
for (int i = 0; i < dict.Count; i++)
{
if (dict[keys[i]] == "")
{
temp.Add(keys[i],0);
dict[keys[i]] = "Moved";
}
}
I think this is what you're looking for:
Dictionary<int, string> dict = new Dictionary<int, string>();
List<int> temp = new List<int>();
dict.Add(123, "");
dict.Add(124, ""); //and so on
foreach (int key in dict.Keys.ToList())
{
if (dict[key] == "")
{
temp.Add(key);
dict[key] = "Moved";
}
}
}
*
First, notice temp is a List, not a Dictionary, since you're just adding the keys, no key => value (this can be changed if you can better explain why you need this as a dictionary)...
Second, notice I used dict.Keys to get all the keys in the dictionary. I also used ToList() so it can work in the foreach loop...
are you getting a compile error for the dictionary definition
Dictionary<int, int> temp = new Dictionary<int, temp>(); // int, temp?
if so,
Dictionary<int, int> temp = new Dictionary<int, int>(); // int, int
?
or, you're getting an error with this:
temp.Add(dict[dict.ElementAt(i).Key]);
because you're adding just a key, with no value. it would be something like
temp.Add(i, dict[i]); ?
if you're just using temp to hold the key values, you don't want a Dictionary, you probably HashSet (only keys, no keys+values)
if you explain exactly what you're trying to solve, this is probably something you can do trivially with a single linq statement?
Why is temp a dictionary? I would use a List<int> with all keys of the dictionary with an empty(null?) value.
List<int> keysWithEmptyValuesInDictionary = dict
.Where(kvp => string.IsNullOrEmpty(kvp.Value))
.Select(kvp => kvp.Key)
.ToList();
foreach (int key in keysWithEmptyValuesInDictionary)
{
dict[key] = "moved";
}

compare dictionaries

i have 3 generic dictionaries
static void Main(string[] args)
{
Dictionary<string, string> input = new Dictionary<string, string>();
input.Add("KEY1", "Key1");
Dictionary<string, string> compare = new Dictionary<string, string>();
compare.Add("KEY1", "Key1");
compare.Add("KEY2", "Key2");
compare.Add("KEY3", "Key3");
Dictionary<string, string> results = new Dictionary<string, string>();
i'd like to take the list of input and compare each value to the compareTo list and if it doesn't exist add it to the results list?
You can use the LINQ Except() method:
foreach (var pair in compare.Except(input))
{
results[pair.Key] = pair.Value;
}
This will perform a set difference (in effect subtracting input from compare and returning what is left over), which we can then add to the results dictionary.
Now, if results has no previous values, and you just want it to be the results from that current operation, you can just do that directly:
var results = compare.Except(input)
.ToDictionary(pair => pair.Key, pair => pair.Value);
This is assuming you want the difference in keys and values. If you had a different value (same key), it would show in the difference.
That is, for your example above results will have:
[KEY2, Key2]
[KEY3, Key3]
But if your example data was:
Dictionary<string, string> input = new Dictionary<string, string>();
input.Add("KEY1", "Key1");
Dictionary<string, string> compare = new Dictionary<string, string>();
compare.Add("KEY1", "X");
compare.Add("KEY2", "Key2");
compare.Add("KEY3", "Key3");
The results would be:
[KEY1, X]
[KEY2, Key2]
[KEY3, Key3]
Due to the fact KEY1's value was different.
If you do want only where keys or values are not contained in the other, you can do the Except on the Keys or Values collections of the dictionary instead.
dict[key] gives you the value whose key is key.
dict.ContainsKey(key) and dict.ContainsValue(value) are methods you can use to check whether a key or a value are in the dictionary. ContainsKey is more time-efficient.

How to use nested dictionary in 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);

Categories

Resources