c# - 显示文本文件中特定数量的记录

标签 c#

我在将文本文件中的 3 条记录加载到数据 GridView 时遇到问题。

private void button1_Click(object sender, EventArgs e)
       {
           using (OpenFileDialog ofd = new OpenFileDialog())
           {
               if (ofd.ShowDialog() == DialogResult.OK && radioButton1.Checked)
               {
                   System.IO.StreamReader file = new System.IO.StreamReader(ofd.FileName);
                   string[] columnnames = file.ReadLine().Split('|');
                   List<string> list = new List<string>();
                   DataTable dt = new DataTable();
                   foreach (string c in columnnames)
                   {
                       dt.Columns.Add(c);
                   }
                   string newline;
                   while ((newline = file.ReadLine()) != null)
                   {
                       DataRow dr = dt.NewRow();
                       string[] values = newline.Split('|');
                       for (int i = 0; i < values.Length; i++)
                       {
                           dr[i] = values[i];

                       }

                       dt.Rows.Add(dr);

                   }
                   file.Close();
                   dataGridView1.DataSource = dt;
               }

           }

我试图让某人选择一个单选按钮(例如“显示 3 条记录”)并打开一个文本文件。然后它将仅在 datagridview 中列出 3 条记录。我可以获取文件来加载文件,但无法弄清楚如何让它只显示文本文件中的 3 条记录。有人可以帮帮我吗?

最佳答案

使用File.ReadLinesTake

var records = File.ReadLines(ofd.FileName).Take(3);

foreach(var record in records)
{
    // do stuff
}

这种方法的优点在于,ReadLines 创建一个迭代器并调用 StreamReader 的管道并单独读取每一行。当与 Take 结合时,它只读取和加载迭代的内容(在本例中为前 3 行)。

您可以在此处找到(并遵循)源代码

https://referencesource.microsoft.com/mscorlib/R/d989485a49fbbfd2.html


其他资源

File.ReadLines Method

Reads the lines of a file.

Enumerable.Take(IEnumerable, Int32) Method

Returns a specified number of contiguous elements from the start of a sequence.

关于c# - 显示文本文件中特定数量的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55506345/

相关文章:

c# - 如何使用 C# 和 iTextSharp 在 pdf 中添加图像?

c# - 在 C# 中直接引用时,如何让类使用默认的 getter/setter?

c# - Bing 代码搜索不起作用,导致 VisualStudio 崩溃

c# - 您是否应该从业务层(或服务层、域模型等)返回 BindingList?

c# - 显示来自多个线程的单个对话框

c# - 通用处理程序的集合——这可能吗?

c# - 使用 MySqlDataAdapter/MySqlCommandBuilder 强制 autoinc 字段

c# - String VS Byte[],内存使用情况

c# - Azure B2C 登录然后返回会引发错误

c# - 将 Entity Framework 对象实例持久化到 xml