gpt4 book ai didi

c# - 读取字符串每个数字c#

转载 作者:太空狗 更新时间:2023-10-29 22:05:15 27 4
gpt4 key购买 nike

假设这是我的 txt 文件:

line1
line2
line3
line4
line5

我正在读取此文件的内容:

 string line;
List<string> stdList = new List<string>();

StreamReader file = new StreamReader(myfile);
while ((line = file.ReadLine()) != null)
{
stdList.Add(line);
}
finally
{//need help here
}

现在我想读取 stdList 中的数据,但只读取每 2 行的值(在这种情况下我必须读取“line2”和“line4”)。谁能把我放在正确的位置?

最佳答案

甚至比 Yuck 的方法更短而且它不需要一次将整个文件读入内存:)

var list = File.ReadLines(filename)
.Where((ignored, index) => index % 2 == 1)
.ToList();

诚然,它确实需要 .NET 4。关键部分是 overload of Where它提供索引以及谓词要作用的值。我们并不真正关心值(这就是我将参数命名为 ignored 的原因)——我们只需要奇数索引。显然,我们在构建列表时关心值,但这没关系 - 它只会被谓词忽略。

关于c# - 读取字符串每个数字c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11763821/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com