阅读量:4
是的,C# 的 for 循环可以处理集合(Collection)。在 C# 中,集合通常是一个实现了 IEnumerable 或 IEnumerator 接口的类,例如 List、Dictionary、HashSet 等。
以下是一些使用 for 循环遍历集合的示例:
- 遍历
List:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
for (int i = 0; i < numbers.Count; i++)
{
Console.WriteLine(numbers[i]);
}
- 遍历
Dictionary:
Dictionary<string, int> fruits = new Dictionary<string, int>
{
{ "apple", 5 },
{ "banana", 8 },
{ "orange", 3 }
};
foreach (KeyValuePair<string, int> fruit in fruits)
{
Console.WriteLine($"{fruit.Key}: {fruit.Value}");
}
注意:虽然这里使用了 foreach 循环,但它实际上是遍历集合的一种简便方法。实际上,foreach 循环底层也是使用 for 循环来遍历集合。因此,你可以根据需要选择使用 for 循环或 foreach 循环来遍历集合。
以上就是关于“c# for循环能处理集合吗”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm