【问题标题】:Reading, modifying and writing a CSV with CSVHelper (variable scope with 'using' )使用 CSVHelper 读取、修改和写入 CSV(使用 \'using\' 的可变范围)
【发布时间】:2023-01-22 10:48:51
【问题描述】:

这是一个关于如何在读取、修改和写入阶段之间共享相同数据列表的一般编码问题。

我也是 C# 的新手和新手,所以我很挣扎。我期望能够:将 CSV 读入变量 records,修改一条或多条记录,然后将修改后的数据作为新的 CSV 写出,但 using 函数存在范围问题。

下面的代码无法编译,因为 records 超出了旨在修改某些数据的 foreach 循环以及我尝试写入修改后的文件时的范围。

我尝试了各种方法来使 records 成为一个更全局的变量,但它们都失败了,我无法理解。

我什至不确定这是解决问题的最佳方法,因此我们将不胜感激。

   private void Btn_Merge_Click(object sender, EventArgs e)
    {
        // Read the CSV into 'records'
        StreamReader reader = new StreamReader(textBox_Shopify.Text);
        using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
        {
            var records = csv.GetRecords<Contact>();
        }

        // We now need to find the record for a specific person and change it
        foreach (Contact customer in records)
        {
            if (customer.Email == "john.dow@business.com")  // Hard-coded while testing
            {
                string Tags = customer.Tags;   // Get the current tags
                                               // If the Lead Marking tag is not already there, add it
                if (!Tags.Contains("Send me Lead Marketing"))
                {
                    // If there are tags already there, append a semi-colon separator
                    if (customer.Tags.Length > 0)
                    {
                        customer.Tags += ";";
                    }
                    customer.Tags += "Send me Lead Marketing";
                    MessageBox.Show(customer.Email + "  Tags: " + customer.Tags);  //Just while I'm testing

                }
            }
            // If the customer is not in the list, add them as a new record

            // To do...
        }

        // We can now write out the modified file
        using (var writer = new StreamWriter(@"C:\temp\Output.csv"))
        using (var outputCSV = new CsvWriter(writer, CultureInfo.InvariantCulture))
        {
            outputCSV.WriteRecords(records);
        }

    }

    public class Contact
    {
        [Name("First Name")]  // This 'attribute' allows the class property First_Name to be matched to the header "First Name"
        public string First_Name { get; set; }
        [Name("Last Name")]
        public string Last_Name { get; set; }
        public string Email { get; set; }
        [Name("Accepts Email Marketing")]
        public string Accepts_Email_Marketing { get; set; }
        public string Company { get; set; }
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public string City { get; set; }
        public string Province { get; set; }
        [Name("Province Code")]
        public string Province_Code { get; set; }
        public string Country { get; set; }
        [Name("Country Code")]
        public string Country_Code { get; set; }
        public string Zip { get; set; }
        public string Phone { get; set; }
        [Name("Accepts SMS Marketing")]
        public string Accepts_SMS_Marketing { get; set; }
        [Name("Total Spent")]
        public string Total_Spent { get; set; }
        [Name("Total Orders")]
        public string Total_Orders { get; set; }
        public string Tags { get; set; }
        public string Note { get; set; }
        [Name("Tax Exempt")]
        public string Tax_Exempt { get; set; }
     }

【问题讨论】:

    标签: c# scope using csvhelper


    【解决方案1】:

    @Mureinik 已经完成一半了。由于 CsvHelper 在您迭代它们时只会 yield 记录,因此您还需要调用 ToList() 或以其他方式迭代 using 语句中的记录。

    IEnumerable<Contact> records;
    
    // Read the CSV into 'records'
    StreamReader reader = new StreamReader(textBox_Shopify.Text);
    using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
    {
        records = csv.GetRecords<Contact>().ToList();
    }
    

    【讨论】:

      【解决方案2】:

      您可以在整个方法的范围内定义 records:

      private void Btn_Merge_Click(object sender, EventArgs e)
      {
          IEnumerable<Contact> records;
      
          // result of the code...
      

      【讨论】:

      • 非常感谢你们两个,因为在头部声明“记录”然后添加 .ToList() 的组合为我解决了这个问题。
      猜你喜欢
      • 2021-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      • 2021-10-03
      • 1970-01-01
      • 2021-05-24
      • 1970-01-01
      相关资源
      最近更新 更多