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

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代码中加载类时,我们必须要include或者require 某个类文件。 但遇到类似的情况,例如: require "Class1.php";...

浅析php fwrite写入txt文件的时候用 \r\n不能换行的问题

今天遇到了一个问题就是用fwrite写入txt文件的时候用 rn不能换行试了很久都没找到办法!突然之间想到一个东东以前看书见过后来还是用这个东东给解决了!现在写出来预防将来忘记也希望能帮...

phpMyAdmin出现无法载入 mcrypt 扩展,请检查PHP配置的解决方法

1、没有正确安装Mysql数据库,在系统服务中Mysql相关的服务没有启动 (请查看正确安装Mysql的方法) 2、在系统的 system32(C:\windows\system32)...

php将字符串随机分割成不同长度数组的方法

本文实例讲述了php将字符串随机分割成不同长度数组的方法。分享给大家供大家参考。具体分析如下: 这里使用php对字符串在指定的长度范围内进行随机分割,把分割后的结果存在数组里面 fu...

php实现转换html格式为文本格式的方法

本文实例讲述了php实现转换html格式为文本格式的方法。分享给大家供大家参考,具体如下: 有时候需要转换html格式的字符串为文本,但又需要保持一定的格式,比如要求段落变成的分段格式就...