foreach items in hashtable - c#

I need to use Hastable (Not List and not Dictionary), and I have many variables with keys. I add keys and variables to class, and use it in my program. But I don't know how to parse Hashtable. I tried this:
Hashtable toboofer = null;
string path = #"my.bin";
FileStream fin = File.OpenRead(path);
try
{
BinaryFormatter bf = new BinaryFormatter();
toboofer = (Hashtable)bf.Deserialize(fin);
for (int i = 0; i <= toboofer.Count; i++ )
//foreach (KeyValuePair<string, string> kvp in toboofer)
{
myclass cl = new myclass();
cl.Fio = toboofer[i].ToString();
cl.About = toboofer[i].ToString();
}
}
but I have an error. When I try string item or cycle for I have an error too.

Hashtable has DictionaryEntry as collection element
foreach (DictionaryEntry entry in toboofer)
{
// do something
}
Make list of myclass from hashtable:
var listOfMyClass = toboofer.Cast<DictionaryEntry>().
Select(e => new myclass()
{ Fio = e.Key.ToString(), About = e.Value.ToString() });

try this hashtable make use if DictionaryEntry, where KeyValuePair generic used by generic dictionary .Net 2 (and onwards)
Aslo note that Hashtable doesnt have generic version of it and Each element in hastable represented by DictionaryEntry
foreach (DictionaryEntry entry in hashtable)
{
Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
}

Related

Iterate through IList<Hashtable> by index in ASP.NET MVC

I am having some trouble iterating through a IList<Hashtable>. I am trying to iterate it by index i.e.:
I have an IList<Hashtable> with 3 different Hashtables in it. I want to foreach each one by IList's index. In example:
I want first to foreach all KeyValuePairs in Hashtable in IList index=0. When finished do some stuff and then foreach all KeyValuePairs in Hashtable in IList index=1 and so on until all Hashtables are iterated through. Currently the code is as follows:
variable data is an IList<Hashtable> with 3 Hashtables in it.
foreach (Hashtable rowData in data[index])
{
some code here...
}
I get the following error:
Unable to cast object of type 'System.Collections.DictionaryEntry' to type 'System.Collections.Hashtable'.
If you want to iterate through an IList<HashTable> via the indexer operator:
IList<Hashtable> data = new List<Hashtable>
{
new Hashtable { { "a", "b"} },
new Hashtable { { "c", "d"}, {"e", "f"} },
new Hashtable { { "g", "h"} },
};
Then you can do the following:
//Iterate through the IList but interested only about the index
foreach (var index in data.Select((_, idx) => idx))
{
//Iterate through the Hashtable which contains DictionaryEntry elements
foreach (DictionaryEntry rowData in data[index])
{
Console.WriteLine($"{rowData.Key} = {rowData.Value}");
}
}
Reference for the Hashtable contains DictionaryEntry items.
The output will be either this:
a = b
c = d
e = f
g = h
or that:
a = b
e = f
c = d
g = h
Try this code
foreach(Hashtable rowData in data)
{
foreach(DictionaryEntry pair in rowData)
{
Console.WriteLine($"{pair.Key} {pair.Value}");
}
}

print OrderedDictionary array values?

Line: gets one line from the file, it's iterate
string[] values = line.split(","); // ex: ["hi, "test", "no", "sup"]
OrderedDictionary od = new OrderedDictionary();
Tuple<int, string[]> innerTuple = new Tuple<int, string[]>(int.Parse(value[0], values);
I cannot seem to find a way to print out the value array. However, I can print out the arrays by using regular dictionary (I don't like how dictionary can mix up the order of insertion).
Try with this:
foreach (DictionaryEntry item in od)
{
Console.WriteLine(item.Key);
Console.WriteLine(item.Value);
}
UPDATE:
If you have a string array as the value then you should try something like this:
foreach (DictionaryEntry item in od)
{
if (item.Value is string[])
{
foreach (string str in (string[])item.Value)
{
Console.WriteLine("A string item: " + str);
}
}
}

IDictionary<String, List<OpenXmlCompositeElement>> - get the List<OpenXmlCompositeElement>?

I'm working with Open XML & I have a IDictionary<String, List<OpenXmlCompositeElement>> structure. I want to work with the List part of the structure but this.map.Values tries to wrap it in an ICollection. How can I get the List part from my structure?
public List<OpenXmlCompositeElement> MapData()
{
//this does not work
return this.map.Values;
}
Since it is a dictionary, it expects you to tell from which key you want the value.
So this would be the code you need, where yourKey is the key you want to retrieve:
public List<OpenXmlCompositeElement> MapData()
{
return this.map["yourKey"];
}
If you have no interest in the key, and the dictionary is just a dictionary because the serializer says so, you could get the first item for example like this:
public List<OpenXmlCompositeElement> MapData()
{
return this.map.Values.First();
}
You can either loop through the dictionary and use the value you would like, or access the List directly using the key (in this case it's a string)
IDictionary<String, List<OpenXmlCompositeElement>> myDictionary;
List<OpenXmlCompositeElement> myList = myDictionary["myKey"];
Where myKey is available in the dictionary.
Alternatively you can loop through
foreach (var item in myDictionary)
{
var key = item.Key;
var value = item.Value
// You could then use `key` if you are unsure of what
// items are in the dictionary
}
Assuming this is your dictionary...
IDictionary<string, List<OpenXmlCompositeElement>> items = ...;
Get a specific List by key...
List<OpenXmlCompositeElement> list = items["key"];
Get the first list in the dictionary...
List<OpenXmlCompositeElement> list = items.Values.First();
Concatenate all lists in the dictionary into a single list...
List<OpenXmlCompositeElement> list = items.SelectMany(o => o).ToList();
foreach(KeyValuePair<string, List<OpenXmlCompositeElement>> kvp in IDictionary)
{
string key = kvp.key
List<OpenXmlCompositeElement> list = kvp.Value;
foreach(OpenXmlCompositeElement o in list)
{
Do anything you need to your List here
}
}
I am working with dictionaries as well, so here is a real example that I am currently working with:
foreach(KeyValuePair<string, List<DataRecords>> kvp in vSummaryResults)
{
string sKey = kvp.Key;
List<DataRecords> list = kvp.Value;
string[] vArr = sKey.Split(',');
int iTotalTradedQuant = 0;
double dAvgPrice = 0;
double dSumQuantPrice = 0;
double dQuantPrice = 0;
double dNumClose = 0;
foreach (DataRecords rec in list)
{
if(vSummaryResults.ContainsKey(sKey))
{
iTotalTradedQuant += rec.iQuantity;
dQuantPrice = rec.iQuantity * rec.dInputTradePrice;
dSumQuantPrice += dQuantPrice;
dAvgPrice = dSumQuantPrice / iTotalTradedQuant;
dNumClose = rec.dNumericClosingPrice;
}
else
{
vSummaryResults.Add(sKey, list);
//dNumClose = rec.dNumericClosingPrice;
}

using a for loop to iterate through a dictionary

I generally use a foreach loop to iterate through Dictionary.
Dictionary<string, string> dictSummary = new Dictionary<string, string>();
In this case I want to trim the entries of white space and the foreach loop does however not allow for this.
foreach (var kvp in dictSummary)
{
kvp.Value = kvp.Value.Trim();
}
How can I do this with a for loop?
for (int i = dictSummary.Count - 1; i >= 0; i--)
{
}
what about this?
for (int i = dictSummary.Count - 1; i >= 0; i--) {
var item = dictSummary.ElementAt(i);
var itemKey = item.Key;
var itemValue = item.Value;
}
KeyValuePair<TKey, TValue> doesn't allow you to set the Value, it is immutable.
You will have to do it like this:
foreach(var kvp in dictSummary.ToArray())
dictSummary[kvp.Key] = kvp.Value.Trim();
The important part here is the ToArray. That will copy the Dictionary into an array, so changing the dictionary inside the foreach will not throw an InvalidOperationException.
An alternative approach would use LINQ's ToDictionary method:
dictSummary = dictSummary.ToDictionary(x => x.Key, x => x.Value.Trim());
You don't need to use .ToArray() or .ElementAt(). It is as simple as accessing the dictionary with the key:
dictSummary.Keys.ToList().ForEach(k => dictSummary[k] = dictSummary[k].Trim());

Update inner Dictionary as Value in outer Dictionary

In such a construction:
Dictionary<myObject, Dictionary<myEnum, secondObject>> myDict;
I use foreach to search all items in outer Dictionary:
foreach (var elem in myDict)
{
//I need to make some modifications in inner Dictionary for chosen myEnum
}
How to do this?
The foreach loop on a Dictionary enumerates key-value pairs. The key is in elem.Key; the value (i.e. your target inner dictionary) is elem.Value.
foreach (var elem in myDict)
{
//I need to make some modifications in inner Dictionary for chosen myEnum
Dictionary<myEnum, secondObject> inner = elem.Value;
inner[myEnum.EnumVal1] = new secondObject(123);
inner[myEnum.EnumVal2] = new secondObject(456);
}
You were close, it seems you just have some confusion over getting access to the inner dictionary?
foreach (var elem in myDict) // var is KeyValuePair<myObject, Dictionary<myEnum, secondObject>>
{
var innerDict = elem.Value; // Value is Dictionary<myEnum, secondObject>
if (innerDict != null)
{
if (innerDict.ContainsKey(enumVal)) // key is myEnum
{
var value = innerDict[enumVal]; // var is secondObject
}
}
}
Since no details is given about myObject or secondObject the following may be too generic but at least may give you an idea:
foreach (var elem in myDict)
{
var temp = elem.Value.Single(p => p.Key == MyEnum.a);
(temp.Value as MySecondObject).anyProperty = anyValue;
}

Categories