如何读取3行文本文件C# - 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();

Java中的OrderByDecending(LINQ)等效项 - java

嗨,我是一名使用Java的C#开发人员。问题很简单:我如何才能将下面的c#代码写入Java并仍能正常工作:myCoffeeList.OrderByDescending(x => x.Name?.ToLower()?.Trim() == sender.Text.ToLower()?.Trim())); 我的sender.Text基本上是一个文本框。文本的…

Linq-在嵌套集合中查找元素 - c#

我有一个通用列表-SupportedTypeGroups。每个SupportedTypeGroup都有SupportedTypes属性(SupportedType的通用列表)。如何构造Linq查询以使用所需名称查找SupportedType? 参考方案 var result = SupportedTypeGroups .SelectMany(g => …

Linq FirstOrDefault评估每次迭代的谓词吗? - c#

如果我有如下声明:var item = Core.Collections.Items.FirstOrDefault(itm => itm.UserID == bytereader.readInt()); 这段代码是在每次迭代时从我的流中读取一个整数,还是只读取一次该整数,将其存储,然后在整个查找过程中使用其值? 参考方案 考虑以下代码: static …

LINQ RemoveAll代替循环 - c#

我有两个for循环,用于从列表中删除项目。我正在为这些循环寻找等效的LINQ语句for (Int32 i = points.Count - 1; i >= 0; i--) { for (Int32 j = touchingRects.Count - 1; j >= 0; j--) { if (touchingRects[j].HitTest(po…

Linq Any()的哪种使用效率更高? - c#

我有一个Linq查询,如下所示:return this._alarmObjectAlarmViolationList .Where(row => row.ObjectId == subId) .Where(row => row.AlarmInternalId == "WECO #1 (StdDev > UCL)") .W…