我得到两个错误“无法分配给'C',因为它是'foreach迭代变量'和”语法错误,值预期“我真的不知道我的错误在哪里?我可以得到一些新鲜的眼睛来识别我的缺陷。
int[] numDictionary = new int[] { 5, 5, 5, 7, 7, 7, 9, 7, 9, 9, 9, 1 };
IDictionary<int, int> count = new SortedDictionary<int, int>();
//count = new SortedDictionary<int, int>();
//int SortedDictionary = count;
foreach (var c in numDictionary)
{
if (c > 0)
{
count[c] = count.[c] + 1;
}
}
//return count.ToString();
Console.WriteLine(count);
Console.ReadKey();
答案 0 :(得分:0)
在foreach
循环中,您无法通过索引访问集合的内容。您可以使用您定义的迭代变量(在本例中为var c
)直接处理集合项。
Console.WriteLine("Contents of numDictionary: ");
foreach (var c in numDictionary)
{
Console.Write(c);
}
但是,无法修改迭代变量 - 只能读取它。如果要迭代数组并修改内容,请使用for
循环。
int[] numDictionary = new int[] { 5, 5, 5, 7, 7, 7, 9, 7, 9, 9, 9, 1 };
for (int i = 0; i < numDictionary.Length; ++i)
{
numDictionary[i] = numDictionary[i] + 1;
}
您可以在this Microsoft Development Network article中找到有关foreach
语句及其与for
语句的关系的更多信息。