C#中foreach用法
来源:互联网 发布:碧素堂面膜怎么样知乎 编辑:程序博客网 时间:2024/05/21 10:27
foreach 语句为数组或对象集合中的每个元素重复一个嵌入语句组。
foreach 语句用于循环访问集合以获取所需信息,但不应用于更改集合内容以避免产生不可预知的副作用。
嵌入语句为数组或集合中的每个元素继续执行。当为集合中的所有元素完成迭代后,控制传递给 foreach 块之后的下一个语句。
可以在 foreach 块的任何点使用 break 关键字跳出循环,或使用 continue 关键字直接进入循环的下一轮迭代。
foreach 循环还可以通过 goto、return 或 throw 语句退出。
示例
在此示例中,使用 foreach 显示整数数组的内容。
class ForEachTest{ static void Main(string[] args) { int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 }; foreach (int i in fibarray) { System.Console.Write(i); } }}
输出
01235813
例1、 计算1到100的和,用foreach语句实现
//用foreach循环实现1到100的和;
int[] Array=new int[100]; for(int i=0; i<100;i++) { Array[i]=i+1; } int sum=0; foreach (int j in Array) { sum=sum+j; }
例2、计算文本框中的最高成绩及对应学生姓名:文本框中格式:姓名=成绩,按Button控件显示结果
<span style="margin: 0px; padding: 0px; border: 0px; background: transparent;"></span>private void button1_Click(object sender, EventArgs e) { //方法一 //string str = txtAllScore.Text; //string[] sp = str.Split(new char[] { '=', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); //int Max = 0; //int each = 0; //int j = 0; //for (int i = 1; i < sp.Length; i = i + 2) //{ // each = Convert.ToInt32(sp[i]); // if (each > Max) // { // Max = each; // j = i; // } //} //txtName.Text = sp[j - 1]; //txtScore.Text = sp[j]; //方法二 //string s = txtAllScore.Text;//按照\r\n进行split string[] lines = txtAllScore.Lines; string maxName = ""; int maxScore = -1; foreach (string line in lines) { if (line == "") { break; } string[] strs = line.Split('='); string name=strs[0]; string strScore=strs[1]; int score=Convert.ToInt32(strScore); if(score>maxScore) { maxName=name; maxScore=score; } } MessageBox.Show(string.Format("{0}是第一名,成绩{1}",maxName,maxScore)); }
0 0
- C#中 Foreach用法
- c#中 foreach 用法
- c#中 foreach 用法
- C#中foreach用法
- c#中 foreach 用法
- C#中foreach用法
- c#中 foreach 用法
- c#中 foreach 用法
- C#中foreach用法
- C#中foreach基本用法
- C#中foreach的用法
- C#中foreach遍历的用法
- C#中 foreach 语句 的用法
- C# Foreach用法
- java中foreach 用法
- php中foreach用法
- Java中foreach用法
- mybatis中foreach用法
- ExtJS 4.2.x 清除Grid的选中状态
- 详解:分布式锁的实现
- URL中传参带有%2F等特殊字符
- IDEA中使用自带GIT工具时SSHKEY免登陆及注意事项
- 新版IDEA的调试功能
- C#中foreach用法
- SPOJ QTREE 树链剖分 边上剖分
- 深入理解Java:SimpleDateFormat安全的时间格式化
- Lucene 面试
- [代码的艺术]20行代码的贪吃蛇
- 微信支付开发准备工作和详细步骤
- jsp页面向springmvc控制器的参数传递
- 深入理解C++的动态绑定和静态绑定
- .net 制作的一个接球游戏