You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#:如何将TextFieldParser读取的数组转为List<T>或直接生成List?

Converting from Array to List for Your Employee Data Reader

Absolutely! Switching from arrays to List<T> is not only possible but will make your code more flexible and easier to maintain. Since you're working with employee data, pairing List<T> with a strongly-typed model class will also add type safety—no more guessing or casting array elements.

Here's a complete, tailored implementation for your WinForms project:

Step 1: Define a Strongly-Typed Employee Model

First, create a class to represent each employee's data. This makes your List<T> usage clean and intuitive:

public class Employee
{
    // Match these properties to the columns in your data.txt file
    public string EmployeeId { get; set; }
    public string FullName { get; set; }
    public string Department { get; set; }
    public decimal Salary { get; set; }
    // Add any other fields you’re parsing from the text file
}

Step 2: Update Your Form Code to Use List

Replace your array logic with a List<Employee> in your button event handler. Here's how the full parsed workflow would look:

public partial class EmployeeInfoGeneratorForm : Form
{
    public EmployeeInfoGeneratorForm()
    {
        InitializeComponent();
    }

    private void btnLoadData_Click(object sender, EventArgs e)
    {
        // Initialize the List instead of a fixed-size array
        List<Employee> employees = new List<Employee>();

        using (TextFieldParser parser = new TextFieldParser("data.txt"))
        {
            parser.TextFieldType = FieldType.Delimited;
            parser.SetDelimiters(","); // Adjust to match your file's delimiter (comma, tab, etc.)
            parser.HasFieldsEnclosedInQuotes = true; // Enable if your values are wrapped in quotes

            // Skip the header row if your data.txt includes one
            parser.ReadLine();

            while (!parser.EndOfData)
            {
                try
                {
                    string[] fields = parser.ReadFields();
                    
                    // Map parsed fields to a new Employee object
                    Employee emp = new Employee
                    {
                        EmployeeId = fields[0],
                        FullName = fields[1],
                        Department = fields[2],
                        Salary = decimal.Parse(fields[3])
                        // Map additional fields as needed
                    };

                    // Add the employee directly to the List
                    employees.Add(emp);
                }
                catch (MalformedLineException ex)
                {
                    MessageBox.Show($"Invalid line detected: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        // Use the List for your needs—examples below:
        // Bind to a DataGridView
        dgvEmployees.DataSource = employees;

        // Iterate through the List
        foreach (Employee emp in employees)
        {
            Console.WriteLine($"Employee: {emp.FullName}, Dept: {emp.Department}");
        }
    }
}

Key Advantages of List Over Arrays

  • Dynamic Growth: No need to predefine a fixed length—List<T> expands automatically as you add items.
  • Type Safety: The model class eliminates casting errors and gives you compile-time checks for property names/types.
  • Built-In Tools: List<T> comes with useful methods like Find(), Sort(), Remove(), and LINQ support for filtering/searching data with minimal code.

If you were previously using untyped arrays (like object[] or string[][]), this approach will make your code far more readable and maintainable long-term.

内容的提问来源于stack exchange,提问作者ADHTML

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:30:32