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

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);
            }

        }

相关文章

linux下为php添加curl扩展的方法

步骤如下: 1. 进到对应扩展目录 # cd /usr/local/src/php-5.2.12/ext/curl 2. 调用phpize程序生成编译配置文件 # /usr/local/...

PHPExcel中文帮助手册|PHPExcel使用方法(分享)

下面是总结的几个使用方法 include 'PHPExcel.php'; include 'PHPExcel/Writer/Excel2007.php'; //或者include...

PHP使用pdo连接access数据库并循环显示数据操作示例

本文实例讲述了PHP使用pdo连接access数据库并循环显示数据操作。分享给大家供大家参考,具体如下: PDO连接与查询: try { $conn = new PDO("odbc:...

php提示Failed to write session data错误的解决方法

本文较为详细的分析了php提示Failed to write session data错误的解决方法。分享给大家供大家参考。具体方法如下: 一、问题: 提示信息:Warning: Fai...

学习php设计模式 php实现原型模式(prototype)

学习php设计模式 php实现原型模式(prototype)

一、意图 用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象 二、原型模式结构图 三、原型模式中主要角色 抽象原型(Prototype)角色:声明一个克隆自身的接口 具体原...