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]);
}
}
}
Related
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
}
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.
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();
I want to get some params from Request
I need from Request.Params all params with text contains "txt" I have more type of text structure:
"ctl00$cphMain$repDelTypes$ctl00$ucDel$txtPhone"
"ctl00$cphMain$repDelTypes$ctl00$ucDel$txtPhone2"
"ctl00$cphMain$repDelTypes$ctl00$ucDel$txtPhone3"
"ctl00$cphMain$repDelTypes$ctl00$ucDel$txtAdr1"
"ctl00$cphMain$repDelTypes$ctl00$ucDel$txtAdr2"
"ctl00$cphMain$repDelTypes$ctl00$ucDel$txtAdr3"
how Get value all text after "txt"
var dictionary = new Dictionary<string, string>();
foreach (var key in Request.Params.AllKeys)
{
if (key.ToString().Contains("txt"))
{
// add to dictionary name and value
// dictionary.Add("name", "val");
}
}
You can do this:
var dictionary = new Dictionary<string, string>();
foreach (var key in Request.Params.AllKeys)
{
if (key.ToString().Contains("txt"))
{
int index = Request.Params[key].LastIndexOf("txt");
Dictionary.Add(key, Request.Params[key].SubString(index));
}
}
Are you asking how to add to the dictionary?
var dictionary = new Dictionary<string, string>();
foreach (var key in Request.Params.AllKeys)
{
if (key.ToString().Contains("txt"))
{
//get the text after "txt"
var index = Request.Params[key].LastIndexOf("txt");
var val = Request.Params[key].SubString(index);
Dictionary.Add(key, val);
}
}
var dictionary = new Dictionary<string, string>();
foreach (var key in Request.Params.AllKeys)
{
if (key.ToString().Contains("txt"))
{
// add to dictionary name and value
dictionary.Add(key.Split(new string[]{"txt"}, StringSplitOptions.None)[1], Request.Params[key]);
}
}
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 });
}