How to add items to a dictionary that contains a dictionary within - c#

I want to add items to a dictionary that contains a dictionary within please refer the code below.
Dictionary<string, Dictionary<string, int>> dict = new Dictionary<string, Dictionary<string, int>>();
foreach (var item in TrainingCourseList)
{
// I have to add item.ID,item.Name,item.Score something like below
dict.Add(item.ID,item.Name,item.Score);
}

I guess Tuple<string, string, int> is the best suit for your case, not Dictionary:
var list = TrainingCourseList
.Select(item => Tuple.Create(item.ID, item.Name, item.Score));

if you want to add an entry to the outer dictionary you have to do something like
Dictionary<string, Dictionary<string, int>> dict = new Dictionary<string, Dictionary<string, int>>();
foreach (var item in TrainingCourseList)
{
// i have to add item.ID,item.Name,item.Score something like below
dict.Add(item.ID,new Dictionary<string,int>{{item.Name,item.Score}};
}

Try
Dictionary<string, Dictionary<string, int>> dict = new Dictionary<string, Dictionary<string, int>>();
foreach (var item in TrainingCourseList)
{
// i have to add item.ID,item.Name,item.Score something like below
dict.Add(item.ID, new Dictionary<string, int> { item.Name, item.Score });
}

Related

Iterating through C# dictionary with KeyValuePair

I try to iterate through dictionary, but it shows me this error:
"cannot convert from 'System.Collections.Generic.KeyValuePair' to 'string'".
Can you tell me how to solve this problem?
Here's the code:
var dict = new SortedDictionary<string, string>();
foreach(KeyValuePair<string, string> ugh in dict){
.............
}
Thank you in advance.
You cannot assign a type KeyValuePair to a string instead you can extract the key and value like this:
var dict = new SortedDictionary<string, string>();
foreach (KeyValuePair<string, string> keyValue in dict)
{
var key = keyValue.Key;
var value = keyValue.Value;
...
...
}
Following should work
foreach (var keyValue in dict)
{
var key = keyValue.Key;
var value = keyValue.Value;
//other logic
}

Error in Reading nested dictionaries C

I want to read nested dictionaries in c#.
declared as follow:
Dictionary<string, double> dict2 =
new Dictionary<string, double>();
Dictionary<string, Dictionary<string, double>> dict1 =
new Dictionary<string, Dictionary<string, double>>();
Dictionary<string, Dictionary<string, Dictionary<string, double>>> globalDict =
new Dictionary<string, Dictionary<string, Dictionary<string, double>>>();
I used the following code to read it:
foreach (var key3 in globalDict.Keys)
{
foreach (var key2 in globalDict[key3].Keys)
{
foreach (var key1 in globalDict[key2].Keys)
{
Console.WriteLine(globalDict[key3][key2][key1]);
}
}
}
but it gives me the following error :
'System.Collections.Generic.KeyNotFoundException'
in this line:
foreach (var key1 in globalDict [key2].Keys)
Any suggestions about the method I used ?
You forgot to first access globalDict[key3], as you are already one Dictionary deep:
foreach (var key3 in globalDict.Keys)
{
foreach (var key2 in globalDict[key3].Keys)
{
Console.WriteLine("Jours {0}", key2);
foreach (var key1 in globalDict[key3][key2].Keys) // here
{
Console.WriteLine(globalDict[key3][key2][key1]);
}
}
}

How to use dictionary with dynamic value? [duplicate]

I have below code in C#
Dictionary<string, object> dObject = new Dictionary<string, object>();
I want to convert dObject to Dictionary<string, string>. How can I do this?
Use the ToDictionary method:
Dictionary<string, string> dString = dObject.ToDictionary(k => k.Key, k => k.Value.ToString());
Here you reuse the key from the original dictionary and you convert the values to strings using the ToString method.
If your dictionary can contain null values you should add a null check before performing the ToString:
Dictionary<string, string> dString = dObject.ToDictionary(k => k.Key, k => k.Value == null ? "" : k.Value.ToString());
The reason this works is that the Dictionary<string, object> is actually an IEnumerable<KeyValuePair<string,object>>. The above code example iterates through the enumerable and builds a new dictionary using the ToDictionary method.
Edit:
In .Net 2.0 you cannot use the ToDictionary method, but you can achieve the same using a good old-fashioned foreach:
Dictionary<string, string> sd = new Dictionary<string, string>();
foreach (KeyValuePair<string, object> keyValuePair in dict)
{
sd.Add(keyValuePair.Key, keyValuePair.Value.ToString());
}
Edit2:
If you are on .Net 2.0 and you can have null values in the dictionary the following should be safe:
Dictionary<string, string> sd = new Dictionary<string, string>();
foreach (KeyValuePair<string, object> keyValuePair in dict)
{
sd.Add(keyValuePair.Key, keyValuePair.Value == null ? "" : keyValuePair.Value.ToString());
}
.NET 3.5:
Dictionary<string, string> result = dObject.ToDictionary(kvp => kvp.Key, kvp => Convert.ToString(kvp.Value));
.NET 2.0:
Dictionary<string, string> result = new Dictionary<string, string>();
foreach (KeyValuePair<string, object> kvp in dObject) result.Add(kvp.Key, Convert.ToString(kvp.Value));
Since you are using .net 2.0:
Dictionary<string, string> dString = new Dictionary<string, string>();
foreach (KeyValuePair<string, object> item in dObject)
{
dString.Add(item.Key, item.Value.ToString());
//here item.Value.ToString() is an example
//you should convert your item to string according to the requirement
}
How about:
Dictionary<string, string> newDictionary = dObject.ToDictionary(k => k.Key, k => (string) k.Value);
In .Net 2.0 probably your best friend is foreach loop:
Dictionary<string, object> dObject = new Dictionary<string, object>();
Dictionary<string, string> newObjects = new Dictionary<string, string>();
foreach (KeyValuePair<string, object> keyValuePair in dObject)
{
newObjects.Add(keyValuePair.Key, keyValuePair.Value.ToString());
}
Dictionary<string, string> dString = dObject.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToString());
It's just idea. You can insert any verifications.

Compare two dictionaries and merge in to other dictionary with keys and values present in both dictionaries

I am working on small utility and as it turns out I have to compare two dictionaries and export the data in Excel in the below format
Key dict1value dict2value
If a key is available in both the dictionaries. My output would be
Key dict1value dict2value
If a key is available in firstdictionary and not in second . My output would be
Key dict1Value "NotAvailable"
If a key is available in second dictionary but not in first . My output would be
key "Not Available" dict2value.
To be more clear, The key column in Excel consists of keys from both the dictionaries.The value columns will have values depending on the availability.
Though the below code is working,I would like to know if I can optimize the performance even more.
Note : Please ignore the bad naming conventions
public void validateTwoDictionaries()
{
Dictionary<string, string> dict1 = new Dictionary<string, string>();
Dictionary<string, string> dict2 = new Dictionary<string, string>();
Dictionary<string, KeyValuePair<string, string>> complexdicts = new Dictionary<string, KeyValuePair<string, string>>();
dict1.Add("A", "1");
dict1.Add("B", "2");
dict2.Add("A", "2");
dict2.Add("C", "3");
dict2.Add("D", "4");
int count1 = dict1.Keys.Count;
int count2 = dict2.Keys.Count;
int maxcount = count2;
if (count1 > count2)
{
maxcount = count1;
}
for (int i = 0; i < maxcount; i++)
{
string dict1Key = string.Empty; string dict2Key = string.Empty;
//need to iterate both the dictionaries at one go.
if (i < count1)
{
dict1Key = dict1.Keys.ElementAt(i);
}
if (i < count2)
{
dict2Key = dict2.Keys.ElementAt(i);
}
// do the work for first dictionary, try to decouple to reuse for the 2nd dict
if (dict1Key != string.Empty)
{
if (!complexdicts.Keys.Contains(dict1Key))
{
if (dict2.Keys.Contains(dict1Key))
{
// Add to the complext dictionary
complexdicts.Add(dict1Key, new KeyValuePair<string, string>(dict1[dict1Key], dict2[dict1Key]));
}
else
{
complexdicts.Add(dict1Key, new KeyValuePair<string, string>(dict1[dict1Key], "Not Available"));
}
}
}
// do the work for second dictionary
if (dict2Key != string.Empty)
{
if (!complexdicts.Keys.Contains(dict2Key))
{
if (dict1.Keys.Contains(dict2Key))
{
// Add to the complext dictionary
complexdicts.Add(dict2Key, new KeyValuePair<string, string>(dict1[dict2Key], dict2[dict2Key]));
}
else
{
complexdicts.Add(dict2Key, new KeyValuePair<string, string>("Not Available", dict2[dict2Key]));
}
}
}
}
dict1 and dict2 are sample dictionaries and complexdicts object is what I want to export to excel.
Please let me know if I can do this in better way.
How about this?
Dictionary<string, string> dict1 = new Dictionary<string, string>();
Dictionary<string, string> dict2 = new Dictionary<string, string>();
Dictionary<string, KeyValuePair<string, string>> complexdicts = new Dictionary<string, KeyValuePair<string, string>>();
dict1.Add("A", "1");
dict1.Add("B", "2");
dict2.Add("A", "2");
dict2.Add("C", "3");
dict2.Add("D", "4");
var allKeys = dict1.Keys.Union(dict2.Keys);
foreach (var key in allKeys)
{
string val1;
if (!dict1.TryGetValue(key, out val1))
{
val1 = "Not Available";
}
string val2;
if (!dict2.TryGetValue(key, out val2))
{
val2 = "Not Available";
}
complexdicts.Add(key, new KeyValuePair<string, string>(val1, val2));
}
How about this?
Dictionary<string, string> dict1 = new Dictionary<string, string>();
Dictionary<string, string> dict2 = new Dictionary<string, string>();
dict1.Add("A", "1");
dict1.Add("B", "2");
dict2.Add("A", "2");
dict2.Add("C", "3");
dict2.Add("D", "4");
var allKeys = dict1.Keys.Union(dict2.Keys);
// case 1
List<Tuple<string, string, string>> unionValues = new List<Tuple<string, string, string>>();
foreach (var key in allKeys)
{
unionValues.Add(new Tuple<string, string, string>(key, dict1.ContainsKey(key) ? dict1[key] : "N/A" , dict2.ContainsKey(key) ? dict2[key] : "N/A"));
}
// case 2
var result = (from key in allKeys
select new Tuple<string, string, string>(key, dict1.ContainsKey(key) ? dict1[key] : "N/A", dict2.ContainsKey(key) ? dict2[key] : "N/A")).ToList();

How to store a collection of Dictionaries?

I need to create a various number of Dictionary<string, string>s in C#; how can I do so?
I've tried using List<Dictionary<string, string>>, but that doesn't work.
See this example:
List<Dictionary<string,string>> list = new List<Dictionary<string,string>>();
Dictionary<string,string> dict1 = new Dictionary<string,string>();
list.Add(dict1);
list.Add(new Dictionary<string,string>());
List<Dictionary<string,string>> does work. Just do it like this:
var d = new List<Dictionary<string,string>>();
var toAdd = new Dictionary<string,string>();
toAdd["Test"] = "Yes";
d.Add(toAdd);
List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
list.Add(new Dictionary<string, string>());
// list[0].Add(...);
Try
List<Dictionary<string, string>> listDic = new List<Dictionary<string, string>>();
Dictionary<string, string> dic = new Dictionary<string, string>();
Dictionary<string, string> dic1 = new Dictionary<string, string>();
dic.Add("key1", "value1");
dic1.Add("key2", "value2");
listDic.Add(dic);
listDic.Add(dic1);
Try,
List<Dictionary<int, string>> a = new List<Dictionary<int, string>>();
Dictionary<int,string> b = new Dictionary<int,string>();
b.Add(1, "Anwer");
a.Add(b);
for (int i = 0; i < a.Count; i++)
foreach (KeyValuePair<int, string> v in a[i])
Console.WriteLine(v.Key + " ------ " + v.Value);

Categories

Resources