使用LINQ逐字读取文本文件 [英] Read text file word-by-word using LINQ

查看:61
本文介绍了使用LINQ逐字读取文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习LINQ,我想使用LINQ逐字阅读文本文件(比如说一本电子书).

I am learning LINQ, and I want to read a text file (let's say an e-book) word by word using LINQ.

这是我能想到的:

static void Main()
        {
            string[] content = File.ReadAllLines("text.txt");

            var query = (from c in content
                         select content);

            foreach (var line in content)
            {
                Console.Write(line+"\n");
            }

        }

这将逐行读取文件.如果我将ReadAllLines更改为ReadAllText,则逐字母读取文件.

This reads the file line by line. If i change ReadAllLines to ReadAllText, the file is read letter by letter.

有什么想法吗?

推荐答案

string[] content = File.ReadAllLines("text.txt");
var words=content.SelectMany(line=>line.Split(' ', StringSplitOptions.RemoveEmptyEntries));
foreach(string word in words)
{
}

您需要添加所需的任何空白字符.使用StringSplitOptions处理连续的空格比我最初使用的Where子句更干净.

You'll need to add whatever whitespace characters you need. Using StringSplitOptions to deal with consecutive whitespaces is cleaner than the Where clause I originally used.

在.net 4中,您可以使用File.ReadLines进行延迟评估,从而在处理大文件时降低RAM使用率.

In .net 4 you can use File.ReadLines for lazy evaluation and thus lower RAM usage when working on large files.

这篇关于使用LINQ逐字读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆