繁体   English   中英

如何读取3行文本文件c#

[英]How to read 3 lines of a text file c#

我设计了一个程序,读取文本文件的指定行,但我想对阅读3线,并把它们在文本框中,例如,读线135只从文本文件中。 谢谢

这是我要修改以读取行而不是单行的代码

  private void Button1_Click(object sender, EventArgs e)
    {
        openFileDialog1.ShowDialog();
        string text = System.IO.File.ReadAllText(openFileDialog1.FileName);
        string line = File.ReadLines(openFileDialog1.FileName).Skip(2).FirstOrDefault();
        TextBox1.Text = line;
    }

尝试Where ,即

string[] lines = File
  .ReadLines(openFileDialog1.FileName)
  .Take(5) // optimization: we want 5 lines at most 
  .Where((line, index) => index == 0 || index == 2 || index == 4)
  .ToArray();

请注意, index从零开始的(第一行有index == 0 )。 在任意索引的情况下

HashSet<int> indexes = new HashSet<int>() {0, 2, 4};

string[] lines = File
  .ReadLines(openFileDialog1.FileName)
  .Take(indexes.Max() + 1) // optimization 
  .Where((line, index) => indexes.Contains(index))
  .ToArray();

System.IO.File.ReadLines() 返回一个 IEnumerable。

在这方面,您可以使用 .ElementAt(index) 来获取特定行,但请记住,第一行的索引为 0。因此,对于您的示例,您实际上需要索引 0、2 和 4。

WhereContains是你的朋友在这里:

Where有一个重载,它将数组的索引作为第二个参数。

var indicesToTake = new int[] { 1, 3, 5 };
string[] lines = File
  .ReadLines(openFileDialog1.FileName)
  .Where((x, i) => indicesToTake.Contains(i))
  .ToArray();

string fullText = string.Join(System.Environment.NewLine, lines); // and TextBox1.Text = fullText;
// or TextBox1.Lines = lines

您还可以使用 linq 构建您想要的索引范围,例如,如果您想要 1 和 100 之间的所有奇数索引:

var indicesToTake = Enumerable.Range(100).Where(i => i % 2 == 1);

正如梅德Bychenko写道,您可以使用其他优化技巧( Take避免所有检查阵列,特别是如果你要排队到低指数10,但是在最后,你更行)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM