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

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判断目录存在的简单方法

PHP判断文件或目录是否存在 file_exists:判断文件是否存在 $file = "check.txt"; if(file_exists($file)) { echo...

老生常谈文本文件和二进制文件的区别

从文件编码的方式来看,文件可分为ASCII码文件和二进制码文件两种。 ASCII文件也称为文本文件,这种文件在磁盘中存放时每个字符对应一个字节,用于存放对应的ASCII码。例如,数567...

php 读取文件乱码问题

网上的解决办法说抓取后用iconv()转码。看后我就觉 得不对劲:一个是不一定编译了iconv库,更大的问题是编码都跟流转换的时候有关(如果用了iconv实际上php转了两次码:流 -&...

thinkphp 验证码 的使用小结

 thinkphp中的验证码是可以直接调用的,非常方便,我们看一下 Think 文件夹下 有一个名为verify.class.php的文件    首先 我们...

PHP如何实现订单的延时处理详解

PHP如何实现订单的延时处理详解

业务需求 订单是我们在日常开发中经常会遇到的一个功能,最近在做业务的时候需要实现客户下单之后订单超时未支付自动取消的功能,刚开始确认了几种方法: 客户端到时间请求取消 服务端...