利用yield关键字输出杨辉三角

本文通过实现杨辉三角的生成,展示了C#中yield关键字的使用方法。该示例帮助理解如何利用yield return来简化集合的创建过程。

最近学习了下python,发现里面也有yield的用法,本来对C#里的yield不甚了解,但是通过学习python,对于C#的yield理解更深了!!

不多说了,小学生水平的表达能力伤不起....

直接上代码:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {

        static void Main(string[] args)
        {
            foreach (var obj in YHSJ(8))
            {
                PrintRow(obj);
            }
            Console.ReadKey();
        }

        /// <summary>
        /// 取得杨辉三角的迭代器
        /// </summary>
        /// <param name="n"></param>
        /// <returns></returns>
        public static IEnumerable<IEnumerable<int>> YHSJ(int n)
        {
            //第一行
            List<int> row = new List<int> { 1 };
            yield return row;
            //第二行
            row = new List<int> { 1, 1 };
            yield return row;
            //第三行及其之后的
            while (n > 0)
            {
                List<int> newrow = new List<int> { 1, 1 };
                int index = row.Count;
                for (int i = 1; i < index; i++)
                {
                    newrow.Insert(1, row[i - 1] + row[i]);
                }
                yield return newrow;
                row = newrow;
                n--;
            }
        }

        /// <summary>
        /// 打印一行数据
        /// </summary>
        /// <param name="row"></param>
        public static void PrintRow(IEnumerable<int> row)
        {
            foreach (int i in row)
            {
                Console.Write(i + "\t");
            }
            Console.WriteLine();
        }
    }
}

  

转载于:https://www.cnblogs.com/a14907/p/5026828.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值