随便玩玩之C# 11 程序控制-循环foreach
随便玩玩之C# 11 程序控制-循环foreach
1.foreach
foreach循环可以遍历集合中的所有项。语法如下:
foreach (类型 变量名 in 集合对象)
{
语句块(循环体)
}
所谓遍历,即将对象(集合)中的所有内容全部输出。
using System;
using System.Collections.Generic;
namespace ForeachExpression
{
internal class Program
{
static void Main(string[] args)
{
//创建一个数组
int[] LotteryNumber = { 06, 12, 26, 28, 29, 32, 15 };
//遍历数组。把数据中的每个数单独输出
foreach (int num in LotteryNumber)
{
Console.WriteLine(num);
}
Console.WriteLine("---------------------------");
// 创建一个字典,并向字典内添加元素(数据)
// 字典键值对(Key,Value),姓名、成绩。
Dictionary<string, int> MathResult = new Dictionary<string, int>();
MathResult.Add("张三", 88);
MathResult.Add("李四", 85);
MathResult.Add("王五", 90);
MathResult.Add("赵六", 78);
// 遍历字典,从字典中输出某个人的数学成绩。
// 一次循环输出一个人的信息,相当于表格中的一行
foreach (var SomeBodyMathResult in MathResult) {
//字典中的键
Console.Write(SomeBodyMathResult.Key);
//字典中键的关联值
Console.WriteLine(SomeBodyMathResult.Value);
}
Console.WriteLine("---------------------------");
// 创建一个匿名对象并填充一些数据。
// 姓名,语文,数学,英语成绩。
var Result = new[]
{
new { name = "张三", chinese = 96,math=88,english=90 },
new { name = "李四", chinese = 93,math=90,english=93 },
new { name = "王五", chinese = 98,math=70,english=85 },
new { name = "赵六", chinese = 92,math=85,english=88 }
};
// 遍历对象,一次循环输出一个人的信息,相当于表格中的一行
foreach (var SomeBodyResult in Result)
{
Console.WriteLine(SomeBodyResult.name);
Console.WriteLine(SomeBodyResult.chinese);
Console.WriteLine(SomeBodyResult.math);
Console.WriteLine(SomeBodyResult.english);
}
Console.WriteLine("---------------------------");
Console.ReadKey();
}
}
}
运行结果。

2.WPF中的DataGrid控件
DataGrid控件是一个数据表格控件。
新建一个WPF项目,解决方案命名为WPFDataGrid。
将工具箱中的Button控件拖放到WPF设计器的空白区域。选中WPF设计器中Button控件,将其Content属性修改为确定。
将工具箱中的DataGrid空间拖放到WPF设计器的空白区域。调整好DataGrid空间的外观大小,将其名称修改为ResultTable。

双击"确定"按钮,WPF转到代码编辑器里,在Button_Click()方法中输入循环代码。
private void Button_Click(object sender, RoutedEventArgs e)
{
var Result = new[]
{
new { name = "张三", chinese = 96,math=88,english=90 },
new { name = "李四", chinese = 93,math=90,english=93 },
new { name = "王五", chinese = 98,math=70,english=85 },
new { name = "赵六", chinese = 92,math=85,english=88 }
};
ResultTable.ItemsSource = Result;
}
运行结果。

运行程序,点击确定。匿名对象中的数据填充到名为ResultTable的DataGrid控件中。
参考资料:
1.foreach
https://learn.microsoft.com/zh-cn/dotnet/csharp/language-reference/statements/iteration-statements
2.datagrid
https://learn.microsoft.com/zh-cn/dotnet/desktop/wpf/controls/datagrid
3.匿名类型
https://learn.microsoft.com/zh-cn/dotnet/csharp/fundamentals/types/anonymous-types

浙公网安备 33010602011771号