使用循环结构访问数据集合
“数据集合”,顾名思义,就是数据的集合,在实际开发中,有两种类型的数据类型我们经常会遇到
- 保存int、float等值类型数据的集合,如“List<int>”
- 保存string和自定义类等引用类型数据的集合,如List<MyClass>,又称为“对象集合”
- 要遍历这两种数据集合,我们可以使用foreach循环
数据集合的遍历
所谓遍历,就是“逐个地访问”
static void ForEachDataCollection()
{
Console.WriteLine("遍历整数集合:");
var IntValues = new List<int>() { 1, 2, 3, 4 };
foreach (var value in IntValues)
{
Console.WriteLine(value);
}
Console.WriteLine("遍历对象集合");
var Myclasses = new List<MyClass>();
for (int i = 0; i < 5; i++)
{
Myclasses.Add(new MyClass()
{
Id = i,
Description = "MyClass对象" + i
});
}
foreach (var obj in Myclasses)
{
Console.WriteLine("{0}:{1}", obj.Id, obj.Description);
}
}
注意事项
使用foreach遍历数据集合时,不要向集合中增删数据
使用foreach还可以循环遍历一个数组
“数组”也可以看成一个数据集合。