C# 使用 LINQ 从文件中读取文本数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2290254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:06:52  来源:igfitidea点击:

Read text data from file using LINQ

c#linqtext

提问by Ondrej Slinták

I have following text file:

我有以下文本文件:

37 44 60
67 15 94
45 02 44

How to read all numbers from this file and save them into two-dimensional array, using LINQ? All I manged to do was creating a simple array with all first values in each row. Is using LINQ in this case a good idea or should I simply load the file normal way and parse it?

如何使用LINQ从此文件中读取所有数字并将它们保存到二维数组中?我要做的就是创建一个简单的数组,每行中包含所有第一个值。在这种情况下使用 LINQ 是一个好主意还是我应该简单地以正常方式加载文件并解析它?

采纳答案by Yuriy Faktorovich

File.ReadAllLines(myFile)
    .Select(l => l.Split(' ').Select(int.Parse).ToArray()).ToArray();

Or:

或者:

List<int[]> forThoseWhoHave1GigFiles = new List<int[]>();
using(StreamReader reader = File.OpenText(myFile))
{
    while(!reader.EndOfStream)
    {
        string line = reader.ReadLine();
        forThoseWhoHave1GigFiles.Add(line.Split(' ')
            .Select(int.Parse).ToArray());
    }
}
var myArray = forThoseWhoHave1GigFiles.ToArray();

And:

和:

File.ReadLines(myFile)
    .Select(l => l.Split(' ')
    .Select(int.Parse).ToArray())
    .ToArray();

In .Net 4.0 and above.

在 .Net 4.0 及更高版本中。

回答by Jonathan

Do you mean something like this?

你的意思是这样的吗?

StreamReader sr = new StreamReader("./files/someFile.txt");

      var t1 =
        from line in sr.Lines()
        let items = line.Split(' ')
        where ! line.StartsWith("#")
        select String.Format("{0}{1}{2}",
            items[1],
            items[2],
            items[3]);

Take a look to this web: LINK

看看这个网站:链接

回答by Thomas Levesque

Just to complete Jonathan's answer, here's how you could implement the Linesextension method :

只是为了完成乔纳森的回答,这里是你如何实现Lines扩展方法:

public static class TextReaderExtensions
{
    public static IEnumerable<string> Lines(this TextReader reader)
    {
        string line;
        while((line = reader.ReadLine()) != null) yield return line;
    }
}