[英]How to: Open double-space delimited file & skip first line
This might be a very simple question for you, but I'm stumped. 对于您来说,这可能是一个非常简单的问题,但是我很困惑。 I'm trying to read text file that has double-space as the delimiter. 我正在尝试读取具有双倍空格作为分隔符的文本文件。
"ColHdr1" "ColHdr2" "ColHdr3" "ColHdr4" "ColHDR5"
"fu" "bar" 1 2 3
"lorem" "ipsum" 5 6 7
I want to put all the lines into a list except the header line. 我想将所有行放入标题行以外的列表中。 This is the code that I have so far: 这是我到目前为止的代码:
string prnFile = @"c:\temp\test.prn";
var fileLines = new List<string>();
foreach (var line in File.ReadAllLines(prnFile, Encoding.GetEncoding(1250)).Skip(1))
{
fileLines.Add(line.Split(new[] { " " },
StringSplitOptions.RemoveEmptyEntries));
}
In the end, I want the list to look like: 最后,我希望列表看起来像:
"fu" "bar" 1 2 3
"lorem" "ipsum" 5 6 7
Any idea what I'm doing wrong? 知道我在做什么错吗?
Your code looks okay to me at first sight, but I'd use LINQ all the way: 乍一看,您的代码对我来说还不错,但我会一直使用LINQ:
var lines = File.ReadLines(prnFile, Encoding.GetEncoding(1250))
.Skip(1)
.Select(line => line.Split(new[] { " " },
StringSplitOptions.RemoveEmptyEntries))
.ToList();
That will get you a List<string[]>
. 那会给你一个List<string[]>
。 It seems to work for me, but note that it won't strip the double-quotes from the start/end of your strings. 它似乎对我有用,但请注意,它不会从字符串的开头/结尾去除双引号。
If you really want a flattened list, that's remarkably easy - just change Select
to SelectMany
: 如果您真的想要一个扁平化的列表,那非常简单-只需将Select
更改为SelectMany
:
var lines = File.ReadLines(prnFile, Encoding.GetEncoding(1250))
.Skip(1)
.SelectMany(line => line.Split(new[] { " " },
StringSplitOptions.RemoveEmptyEntries))
.ToList();
That gives you: 那给你:
"fu"
"bar"
1
2
3
"lorem"
"ipsum"
5
6
7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.