C#中foreach基本用法

foreach 语句为数组或对象集合中的每个元素重复一个嵌入语句组。

foreach 语句用于循环访问集合以获取所需信息,但不应用于更改集合内容以避免产生不可预知的副作用。

嵌入语句为数组或集合中的每个元素继续执行。当为集合中的所有元素完成迭代后,控制传递给 foreach 块之后的下一个语句。

可以在 foreach 块的任何点使用 break 关键字跳出循环,或使用 continue 关键字直接进入循环的下一轮迭代。

foreach 循环还可以通过 gotoreturn  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控件显示结果
	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));

        }


  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值