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
Read text data from file using LINQ
提问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
回答by Thomas Levesque
Just to complete Jonathan's answer, here's how you could implement the Lines
extension method :
只是为了完成乔纳森的回答,这里是你如何实现Lines
扩展方法:
public static class TextReaderExtensions
{
public static IEnumerable<string> Lines(this TextReader reader)
{
string line;
while((line = reader.ReadLine()) != null) yield return line;
}
}