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
}
Related
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]);
}
}
}
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 have this dictionary Dictionary<TableKey, string> where TableKey is an enum type.
I'm trying to populate the dictionary with data from a DataSet object that I acquire during an sql query
DataSet resultSet = Utils.RunQuery(sqlQuery);
if (resultSet.Tables.Count > 0)
{
foreach (DataRow row in resultSet.Tables[0].Rows)
{
// Makes the dictionary with populated keys from enum
Dictionary<TableKey, string> dic = new Dictionary<TableKey, string>();
foreach (TableKey key in Enum.GetValues(typeof(TableKey)))
dic.Add(key, "");
// the foreach loop in question, which should insert row data into the dic
foreach (TableKey key in Enum.GetValues(typeof(TableKey)))
dic[key] = row[key.GetName()].ToString(); // This line does not work!
// adds dictionary to my list of dictionaries
latestEntryList.Add(dic);
}
}
I'm trying to replace this by using the forloop in the above code.
dic[TableKey.Barcode] = row["Barcode"].ToString();
dic[TableKey.FullName] = row["FullName"].ToString();
dic[TableKey.Location] = row["Location"].ToString();
dic[TableKey.Notes] = row["Notes"].ToString();
dic[TableKey.Category] = row["Category"].ToString();
dic[TableKey.Timestamp] = row["Timestamp"].ToString();
dic[TableKey.Description] = row["Description"].ToString();
EDIT: Maybe there is a way to combine the two foreach loops into one.
EDIT: I need to get the string name of the enum and the key value itself.
public enum TableKey
{
Barcode = 0,
FullName = 1,
Location = 2,
Notes = 3,
Category = 4,
Timestamp = 5,
Description = 6
}
Solution
DataSet resultSet = Utils.RunQuery(sqlQuery);
if (resultSet.Tables.Count > 0)
{
foreach (DataRow row in resultSet.Tables[0].Rows)
{
Dictionary<TableKey, string> dic = new Dictionary<TableKey, string>();
foreach (TableKey key in Enum.GetValues(typeof(TableKey)))
dic.Add(key, row[key.ToString()].ToString());
latestEntryList.Add(dic);
}
}
dic[Key] = row[key.ToString()].ToString();
Edit: I see a comment with this too. If that's made into answer, I'll delete this :)
Try the following:
foreach (TableKey key in Enum.GetValues(typeof(TableKey)))
{
dic[key] = row[key.ToString("G")].ToString();
}
I think you can do it in one loop :
// Makes the dictionary with populated keys from enum
Dictionary<TableKey, string> dic = new Dictionary<TableKey, string>();
foreach (TableKey key in Enum.GetValues(typeof(TableKey)))
dic.Add(key, row[Enum.GetName(typeof(Direction), key)].ToString());
Edit:
To get the enum 'value', you just cast it to int :
// Makes the dictionary with populated keys from enum
Dictionary<TableKey, string> dic = new Dictionary<TableKey, string>();
foreach (TableKey key in Enum.GetValues(typeof(TableKey)))
dic.Add(key, row[(int) key].ToString());
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 });
}