This is my code :
Hashtable actualValues = new Hashtable();
actualValues.Add("Field1", Int32.Parse(field1.Value));
actualValues.Add("Field2", Int32.Parse(field2.Value));
actualValues.Add("Field3", Int32.Parse(field3.Value));
bool isAllZero = true;
foreach (int actualValue in actualValues)
{
if (actualValue > 1)
isAllZero = false;
}
if (isAllZero)
{
}
but I get this exception System.InvalidCastException: Specified cast is not valid.
on Line 6, close to foreach
.
Where am I wrong?
Hashtable returns returns an IEnumerator of type IDictionaryEnumerator
, the elements returned by the MoveNext method are of type DictionaryEntry
, not int - your foreach loop is invalid.
Try the following:
bool isAllZero = actualValues.Values.Cast<int>().All(v => v == 0);
Or without Linq:
bool isAllZero = true;
foreach (int actualValue in actualValues.Values)
{
if (actualValue != 0)
{
isAllZero = false;
break;
}
}