找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1552|回复: 0
打印 上一主题 下一主题

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

[复制链接]

2560

主题

2560

帖子

7622

积分

论坛元老

Rank: 8Rank: 8

积分
7622
跳转到指定楼层
楼主
发表于 2018-2-14 08:20:49 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

            1.迭代文件的行
[U]复制代码[/U] 代码如下:
        public static IEnumerable 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.使用迭代器和谓词对文件中的行进行筛选
[U]复制代码[/U] 代码如下:
       public static IEnumerable where(IEnumerable source, Predicate predicate)
        {
            if (source == null || predicate == null)
            {
                throw new ArgumentNullException();
            }
            return WhereImplemeter(source, predicate);
        }
       private static IEnumerable WhereImplemeter(IEnumerable source, Predicate predicate)
        {
            foreach (T item in source)
            {
                if (predicate(item))
                {
                    yield return item;
                }
            }
        }
        static void Main()
        {
            IEnumerable lines = File.ReadAllLines(@"your file name");
            Predicate predicate = delegate(string line)
            {
                return line.StartsWith("using");
            };
            foreach (string str in where(lines, predicate))
            {
                Console.WriteLine(str);
            }
        }
            
            
您可能感兴趣的文章:
  • ruby 迭代器使用方法
  • PHP设计模式之迭代器模式的深入解析
  • PHP迭代器实现斐波纳契数列的函数
  • PHP迭代器的内部执行过程详解
  • python迭代器的使用方法实例
            
  • 分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    用户反馈
    客户端