簡體   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