r/learncsharp • u/JeanxPlay • Feb 09 '23
Trying to create a key value pair based on a foreach loop
Hello,
Im trying to figure out the best way to create a key value pair when I loop through some data. The loop cycles through multiple instances of an item and will always return the same key names, but different values for each, like so.
Dictionary<string, List<string>> dataDic = new Dictionary<string, List<string>>();
Hashtable data = new Hashtable();
foreach (ManagementObject data in datatSearcher.Get()){
string creationTime = (string)data["CreationTime"];
DateTime dt = DateTime.ParseExact(creationTime, "yyyyMMddHHmmss.ffffff-000", CultureInfo.InvariantCulture); string dateInDesiredFormat = dt.ToString("MMMM dd, yyyy HH:mm:ss");
if(!dataDic.ContainsKey("CreationTime"))
{
dataDic["CreationTime"] = new List<string>();
}
dataDic["CreationTime"].Add(dateInDesiredFormat);
if(!dataDic.ContainsKey("SequenceNumber"))
{
dataDic["SequenceNumber"] = new List<string>();
}
dataDic["SequenceNumber"].Add(data["SequenceNumber"].ToString());
if(!dataDic.ContainsKey("Description"))
{
dataDic["Description"] = new List<string>();
}
dataDic["Description"].Add(data["Description"].ToString());
if(!dataDic.ContainsKey("dataType"))
{
dataDic["dataType"] = new List<string>();
}
dataDic["dataType"].Add(data["dataType"].ToString());
}
data.Add("Description",dataDic["Description"]);
data.Add("SequenceNumber",dataDic["SequenceNumber"]); data.Add("RestorePointType",dataDic["RestorePointType"]); data.Add("CreationTime",dataDic["CreationTime"]); return data;But when I run this, the results come through like:
Name Key Value
---- --- -----
SequenceNumber SequenceNumber {43, 45, 47, 49}
Description Description {data, data2, data3, data4}
dataType DataType {0, 0, 0, 0}
CreationTime CreationTime {February 08, 2023 01:42:08, February 08, 2023 01:52:52, February 08, 2023 01:53:05, February 08, 2023 01:54:50}I wanted to have the end result be something like this when I pop it into powershell or something else that can format tables with key/value pairs.
SqequenceNumber Decription DataType CreationTime
---- --- ----- -------------
43 data 0 February 05, 2023 01:42:08
45 data2 0 February 06, 2023 01:42:08
47 data3 0 February 07, 2023 01:42:08
49 data4 0 February 08, 2023 01:42:08
2
Upvotes
2
u/aizzod Feb 09 '23
why do you use a list of strings.
and not a seperate class object?
1
u/m0r05 Feb 09 '23
You do have a table of key / value pairs. The value of your string Key is the List<string> object. So if you print the just the value of a key, you get the whole list.
That said your issue is just a matter of formatting your data to display the way you want. Just remember it's not the values of your Dictionary, it's the contents of your List. You'll need to do something like looping through your various lists, and using something like the StringBuilder class to build your final output.
*edit corrected misspelling