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

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使用header()输出图片缓存实例

本文实例讲述了PHP使用header()输出图片缓存的方法。分享给大家供大家参考。具体分析如下: 在我们生成验证码时会需要直接输入图片,通常会使用到header("Content-typ...

php之Memcache学习笔记

1、win下安装,memcached -d installwin下启动,memcached -d start关闭,memcached -d stop 1_1、三种方式访问memcache...

php实现二进制和文本相互转换的方法

本文实例讲述了php实现二进制和文本相互转换的方法。分享给大家供大家参考。具体如下: 这段代码包含两个函数,bin2text,二进制转换为文本,text2bin,文本转换成二进制 &...

PHP 文件上传进度条的两种实现方法的代码

目前我知道的方法有两种,一种是使用PHP的创始人 Rasmus Lerdorf 写的APC扩展模块来实现(http://pecl.php.net/packa...

PHP strripos函数用法总结

php strripos()函数 语法 作用:寻找某字符串中某字符最后出现的位置,不区分大小写 语法: strripos(string,find,start) 参数: string...