使用迭代器 遍历文件信息的详解

yipeiwu_com5年前PHP代码库
1.迭代文件的行
复制代码 代码如下:

        public static IEnumerable<string> ReadLines(string fileName)
        {
            using (TextReader reader = File.OpenText(fileName))
            {
                string line;
                if ((line = reader.ReadLine()) != null)
                {
                    yield return line;
                }
            }
        }
        static void Main()
        {
            foreach (string line in Iterator.ReadLines(""))
            {
                Console.WriteLine(line);
            }
        }

2.使用迭代器和谓词对文件中的行进行筛选
复制代码 代码如下:

       public static IEnumerable<T> where<T>(IEnumerable<T> source, Predicate<T> predicate)
        {
            if (source == null || predicate == null)
            {
                throw new ArgumentNullException();
            }
            return WhereImplemeter(source, predicate);
        }
       private static IEnumerable<T> WhereImplemeter<T>(IEnumerable<T> source, Predicate<T> predicate)
        {
            foreach (T item in source)
            {
                if (predicate(item))
                {
                    yield return item;
                }
            }
        }
        static void Main()
        {
            IEnumerable<string> lines = File.ReadAllLines(@"your file name");
            Predicate<string> predicate = delegate(string line)
            {
                return line.StartsWith("using");
            };
            foreach (string str in where(lines, predicate))
            {
                Console.WriteLine(str);
            }

        }

相关文章

php常用字符串输出方法分析(echo,print,printf及sprintf) 原创

本文讲述了php常用字符串输出方法。分享给大家共大家参考,具体如下: 1. echo用法:可用echo 直接输出,也可以用echo()输出,无返回值 $string="<b&g...

ajax 的post方法实例(带循环)

ajax 的post方法实例(带循环)

用上循环就是为了在数据发送前进行合理的处理,解决在脚本语言对数据进行另外需求处理时出现的超时现象。处于对ajax认识未深,如有说得不对或不到位的,还请指教。     ajax中的po...

php实现计算百度地图坐标之间距离的方法

本文实例讲述了php实现计算百度地图坐标之间距离的方法。分享给大家供大家参考,具体如下: 下面是网上的代码,使用的时候需要进行些许修改 第一个函数是获得范围,参数为纬度经度半径 第二个函...

浅谈PHP错误类型及屏蔽方法

程序只要在运行,就免不了会出现错误,错误很常见,比如Error,Notice,Warning等等。在PHP中,主要有以下3种错误类型。 1.注意(Notices) 这些都是比较小而且不严...

php 7新特性之类型申明详解

前言 PHP7 将类型申明变成了可能,PHP 7 支持的形参类型申明的类型有以下几种 整型 浮点型 字符串型 布尔类型 函数形参与返回类型声明demo 如下...