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

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绘图技术

1、图片格式:目前网站开发常见的图片格式有gif,jpg/jpeg,png .....区别:•gif 图片压缩率高,但是只能显示256色,可能造成颜色的丢失,可以显示动画&#...

PHP使用XMLWriter读写xml文件操作详解

本文实例讲述了PHP使用XMLWriter读写xml文件操作。分享给大家供大家参考,具体如下: 米扑科技旗下的多个产品,需要脚本自动生成sitemap.xml,于是重新温习一遍PHP X...

php数组函数序列之in_array() - 查找数组中是否存在指定值

in_array()定义和用法 in_array() 函数查找数组中是否存在指定值。 语法 in_array(value,array,type)参数 描述 value 必需。规定要在数组...

php验证码生成代码

验证码通常是用来安全保证我们网站注册或登录不被注入的,但为了更安全我们通常会生成一些混合验证码了,下面一起来看看例子. 在我们开发登录模块或者是论坛的灌水模块的时候,为了防止恶意提交,需...

WordPress中创建用户角色的相关PHP函数使用详解

WordPress中创建用户角色的相关PHP函数使用详解

WordPress 默认有 “订阅者”、“投稿者”、“作者”、“编辑” 和 “管理员” 五个用户角色,权限由低到高,但默认的五个角色可能不够我们用,这时可以使用 add_role() 函...