C# 如何检查哈希表值是否全部为0?
这是我的代码:C# 如何检查哈希表值是否全部为0?,c#,hashtable,cycle,C#,Hashtable,Cycle,这是我的代码: 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 (in
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)
{
}
但是我得到了这个异常System.InvalidCastException:指定的强制转换无效。
在第6行,靠近foreach
我哪里错了?当你循环一个哈希表时,你会得到一个
字典entry
,而不是int
foreach (DictionaryEntry entry in actualValues)
{
if (((int)entry.Value) > 1)
isAllZero = false;
}
假设您可以使用Linq
bool isAllZero = Hashtable.Cast<DictionaryEntry>().All(pair => (int)pair.Value == 0);
Hashtable返回的IEnumerator类型为
IDictionaryEnumerator
,MoveNext方法返回的元素类型为DictionaryEntry
,而不是int-foreach循环无效
请尝试以下操作:
bool isAllZero = actualValues.Values.Cast<int>().All(v => v == 0);
“实际值”的类型是什么?请显示
实际值的声明(字符串,int),您可以在代码中看到!你在哪一行得到异常?在哪一行抛出异常?从isAllZero
的语义来看,比较可能应该用=
-但是这只是一个猜测。哈希表返回一个字典entry
@DanielA.White谢谢你发现了这一点。你还必须抛出Value
。哈希表不包含Cast的定义:(@markzzz通用字典是强类型的,允许在编译时检测大量错误。此外,它们实现了强类型IEnumerable,允许在我的答案中写入第二个代码块(更短…否?)I get ICollection不包含All()的定义…!它不起作用:(@markzzz)您是否在系统.Linq
命名空间中包含了用于拉入的函数,并包含了对Cast
的调用?
bool isAllZero = actualValues.Values.Cast<int>().All(v => v == 0);
bool isAllZero = true;
foreach (int actualValue in actualValues.Values)
{
if (actualValue != 0)
{
isAllZero = false;
break;
}
}