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

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高级编程实例:编写守护进程

1.什么是守护进程 守护进程是脱离于终端并且在后台运行的进程。守护进程脱离于终端是为了避免进程在执行过程中的信息在任何终端上显示并且进程也不会被任何终端所产生的终端信息所打断。 例如 a...

snoopy 强大的PHP采集类使用实例代码

下载地址: https://www.jb51.net/codes/33397.html Snoopy的一些特点: 1抓取网页的内容 fetch 2 抓取网页的文本内容 (去除HTML标签...

整理的9个实用的PHP库简介和下载

1. ReCAPTCHA The reCAPTCHA 库让你可以为网站创建高级的 CAPTCHA 系统,这个系统其实是用来生成验证信息的,甚至包括语音验证。当然还有 reCAPTCHA...

PHP的Yii框架中行为的定义与绑定方法讲解

定义行为 要定义行为,通过继承 yii\base\Behavior 或其子类来建立一个类。如: namespace app\components; use yii\base\Beh...

php+Memcached实现简单留言板功能示例

php+Memcached实现简单留言板功能示例

本文实例讲述了php+Memcached实现简单留言板功能。分享给大家供大家参考,具体如下: MyPdo.php <?php class MyPdo{ privat...