Getting value and name from Enum in foreach loop - c#

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

Related

How to get value of a specific value of a list in C#

var ctsDB = mooe.Files66.ToList();
Dictionary<string, string> mappedfields = new Dictionary<string, string>();
Dictionary<string, string> ctsfieldsValue = new Dictionary<string, string>();
for (int i = 0; i < ctsDB.Count; i++)
{
foreach(var item in mappedfields) {
// this line returns the item.key string not the value of it.
// item.key is the column name
var rowValue = mooe.Files66.Select(k = >item.Key).ToList();
// ctsfieldsValue.Add(item.Value, rowValue);
ctsfieldsValue.ToList();
}
}
I want to iterate through ctsDB List and get the row value of a specific
column like this:
if ctsDB [i] = fileID Field612 Fiel613
and I have these column names in the value field of ctsfieldsValue.
I want to iterate on ctsDB[i] to get the value of column Field612 only.
Can anyone provide a thought?
var ctsDB = mooe.Files66.ToList();
var mappedfields = new Dictionary<string, string>(); // I assume this is not empty in your real code.
var ctsfieldsValue = new List<Dictionary<string, string>>();
foreach (var row in ctsDB)
{
var d = new Dictionary<string, string>();
foreach (var mapping in mappedfields)
{
var v = row[mapping.Key]; //throws if not found
d[mapping.Value] = v;
}
ctsfieldsValue.Add(d);
}

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
}

C# KeyValue foreach column in row

I am here today trying to work out how I can do this. I have the code below to look through each column in a DataRow, but how can I access the key AND value? I want to assign it to a dictionary in the class but I can't seem to get both of them, the only way I can get anything is by calling:
var columnValue = playerDataRow[column];
Here is the full thing:
using (var mysqlConnection = Sirius.GetServer().GetDatabaseManager().GetConnection())
{
mysqlConnection.SetQuery("SELECT * FROM `users` WHERE `auth_ticket` = #authTicket LIMIT 1");
mysqlConnection.AddParameter("authTicket", authTicket);
var playerDataTable = mysqlConnection.GetTable();
foreach (DataRow playerDataRow in playerDataTable.Rows)
{
foreach (DataColumn column in playerDataTable.Columns)
{
var columnValue = playerDataRow[column];
}
}
}
foreach (DataRow playerDataRow in playerDataTable.Rows)
{
var myDic = new Dictionary<string, object>();
foreach (DataColumn column in playerDataTable.Columns)
{
myDic.Add(column.ColumnName, playerDataRow[column]);
}
}
the variable column will be the key and the value will be columnValue
looks that you only want one row of output - perhaps for this specific user based on auth_ticket
here is an example of how to get all values for this row into a Dictionary of strings (I'm converting all data to strings by the way just for this example)
var htRowValues = new Dictionary<string,string>();
using (var mysqlConnection = Sirius.GetServer().GetDatabaseManager().GetConnection())
{
mysqlConnection.SetQuery("SELECT * FROM `users` WHERE `auth_ticket` = #authTicket LIMIT 1");
mysqlConnection.AddParameter("authTicket", authTicket);
var playerDataTable = mysqlConnection.GetTable();
foreach (DataRow playerDataRow in playerDataTable.Rows)
{
foreach (DataColumn column in playerDataTable.Columns)
{
var columnValue = playerDataRow[column];
htRowValues[column.ColumnName]=System.Convert.ToString(columnValue);
}
}
}
now you have all column values in the dictionary for this one row of data.

Compare Dictionary Key of type string to another string in C#

I'm actually trying to check if a string is equal to any of the key's in my Dictionary object.
Here is what I have done so far:
using (var oStreamReader = new StreamReader(path))
{
Dictionary<String, String> typeNames = new Dictionary<string, string>();
typeNames.Add("Kind","nvarchar(1000)");
typeNames.Add("Name","nvarchar(1000)");
DataTable oDataTable = new DataTable();
var headLine = oStreamReader.ReadLine().Trim().Replace("\"", "");
var columnNames = headLine.Split(new[] { ';' });
String[] oStreamDataValues;
/*
*create DataTable header with specific datatypes and names
*/
int countCol = 0;
foreach (string readColumn in columnNames)
{
if ((readColumn.ToString().Replace("\"", "").CompareTo(typeNames) == true))
{
// this comparison doesn't work
}
}
}
I am not quite sure what exactly you are trying to achieve. If you have a C# dictonary you can use linq to check for values that match the required value, e.g.
string valueToCompare = "Value to match";
Dictionary<string, string> dict = new Dictionary<string, string>
{
{"Key 1", "A value"},
{"Key 2", "Another value"}
};
bool found= dict.Values
.Any(value
=>
value.Equals(valueToCompare,
StringComparison.CurrentCultureIgnoreCase)
);
Since you want check if exist an entry in your Dictionary that as the same key of one of the values in your columnNames object I suggest you to use ContainsKey method
Dictionary<string, string> d = new Dictionary<string, string>();
string keyvalue;
if (d.ContainsKey("value to find"))
{
if (d.TryGetValue("value to find", out keyvalue))
{
//// here keyvalue variable has the value
}
else
{
///value is null or throws exception
}
}
else
{
////key no exists
}
I have solved this (by inspiration of Paul Houlston and Thomas Lielacher)
string headLine = oStreamReader.ReadLine().Trim().Replace("\"", "");
string columnNames = headLine.Split(new[] { ';' });
foreach (string readColumn in columnNames)
{
if (typeNames.Keys.Contains(readColumn, StringComparer.CurrentCultureIgnoreCase) == true)
{
DataColumn oDataColumn = new DataColumn(readColumn,typeof(System.String));
oDataTable.Columns.Add(oDataColumn);
}
}

Add to dictionary some params from request

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

Categories

Resources