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]);
}
}
Related
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);
}
I'm working on a project where I want to build tokens from a JSON Array.
//Data fed to the system
{"Fruits":[{"Number":"111", "Name":"Apple"}, {"Number":"112", "Name":"Orange"},{"Number":"113", "Name":"Peach"}]}
//serializes the http content to a string
string result = Request.Content.ReadAsStringAsync().Result;
//deserializes result
Dictionary<string, dynamic> data = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(result);
//builds custom tokens
var customTokens = new Dictionary<string, object>();
foreach (var dataField in data)
{
if (dataField.Value is JArray)
{
string nameValue = "";
foreach (JObject content in dataField.Value.Children<JObject>())
{
foreach (JProperty prop in content.Properties())
{
nameValue += prop.Name.ToString() + " : " + prop.Value.ToString();
}
}
customTokens.Add($"{dataField.Key}", nameValue);
}
}
The above code managed to create token $Fruits.
But i also want to achieve token $Number and $Name, where values of each token is from the concatenated values of same key. Example, If I use the "$Number", it will be replaced by 111, 112, 113 and If I use the $Name, it will be replaced by Apple, Orange, Peach.
Also, I'm not using any strongly type models as I don't know what data will be fed to the system.
Any help?
There are a few minor changes to your code to achieve this. First make your dictionary look like this:
var customTokens = new Dictionary<string, List<string>>();
Then, when you loop over all the properties in the array, check if the property has been added, and if not add it.
foreach (JProperty prop in content.Properties())
{
if(customTokens.ContainsKey(prop.Name))
{
customTokens[prop.Name].Add(prop.Value.ToString());
}
else
{
customTokens.Add(prop.Name, new List<string> { prop.Value.ToString() });
}
}
At the end you have a dictionary where the key is the property name and the value is a List<string> - this can be concatenated together:
foreach(var item in customTokens)
{
Console.WriteLine(item.Key + ":" + String.Join(",", item.Value));
}
Or, if you really want it in a dictionary of concatenated strings just do this
var finalResult = customTokens.ToDictionary(k => k.Key, v => String.Format(",",v.Value));
Note you'll need to add using System.Linq to the top of your file to use ToDictionary
Final test code:
var result = "{ \"Fruits\":[{\"Number\":\"111\", \"Name\":\"Apple\"}, {\"Number\":\"112\", \"Name\":\"Orange\"},{\"Number\":\"113\", \"Name\":\"Peach\"}]}";
Dictionary<string, dynamic> data = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(result);
var customTokens = new Dictionary<string, List<string>>();
foreach (var dataField in data)
{
if (dataField.Value is JArray)
{
foreach (JObject content in dataField.Value.Children<JObject>())
{
foreach (JProperty prop in content.Properties())
{
if(customTokens.ContainsKey(prop.Name))
{
customTokens[prop.Name].Add(prop.Value.ToString());
}
else
{
customTokens.Add(prop.Name, new List<string> { prop.Value.ToString() });
}
}
}
foreach(var item in customTokens)
{
Console.WriteLine(item.Key + ":" + String.Join(",", item.Value));
}
}
}
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'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);
}
}
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());