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

yipeiwu_com6年前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

一、引论 PHP,一门最近几年兴起的web设计脚本语言,由于它的强大 和可伸缩性,近几年来得到长足的发展,php相比传统的asp网站,在速度上有绝对的优势,想mssql转6万条...

PHP 日期时间函数的高级应用技巧

PHP 日期时间函数的高级应用技巧

PHP的日期时间函数date() 1,年-月-日 echo date('Y-m-j'); 2007-02-6 echo date('y-n-j'); 07-2-6 大写Y表示年四...

PHP实现的封装验证码类详解

用PHP写一个验证码类,并进行封装。类名: validationcode.class.php代码如下:复制代码 代码如下:<?php class ValidationCo...

php数据库操作model类(使用__call方法)

本文实例讲述了php数据库操作model类。分享给大家供大家参考,具体如下: 该数据库操作类使用__call()方法实现了数据的查找功能。 代码如下: <?php /*...

php获取微信基础接口凭证Access_token

本文为大家分享了php获取微信基础接口凭证Access_token的具体代码,供大家参考,具体内容如下 access_token是公众号的全局唯一票据,公众号调用各接口时都需使用acce...