Otto Rahn
Otto Rahn

Reputation: 173

The code is duplicated when getting values from CSV with С# CSVHELPER

The code is duplicated in the method when reading CSV. How to remove duplicates and why do they occur? Writing to CSV occurs without them, but when reading, duplicates begin:

Method:

public class Program
{

    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public Product(int id, string name)
        {
            Id = id;
            Name = name;
        }
    }

    public static void Main(string[] args)
    {
        Research();
    }

    public static void Research()
    {

            using (var writer = new StreamWriter("C:\\Users\\Saint\\Desktop\\TaskRetail\\file.csv", false, Encoding.UTF8))
            using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
            {
                csv.WriteRecords(products);
            }

            var config = new CsvConfiguration(CultureInfo.InvariantCulture) 
            { 
            Delimiter = ",",
            PrepareHeaderForMatch = header => header.Header.ToLower()
            };

            using (var reader = new StreamReader("C:\\Users\\Saint\\Desktop\\TaskRetail\\file.csv", Encoding.UTF8))
            using (var csv = new CsvReader(reader, config))

            {
                var records = csv.GetRecords<Product>();

                foreach (var record in records)
                {
                    Console.WriteLine($"{record.Id} {record.Name}");
               }
            }
        }
    }
}

output to the console:

enter image description here

Upvotes: 0

Views: 397

Answers (1)

David Specht
David Specht

Reputation: 9094

The issue is you have included the writing and reading of the CSV file in your loop that is creating the products. Your first product is created, it is written to the CSV file and then it is read and printed to your Console. The loop continues and your second product is created. Product 1 and product 2 are written to the CSV file and then they are both read from the CSV file and printed to your Console. This continues for each product that is created, which is why you are showing the duplicates in your console. You need to close your for loop before you write to file.csv

for (var i = 0; i < count; i++)
{
    var element = xmlDoc.Item(i);
    var id = int.Parse(element.Attributes.GetNamedItem("id").Value);
    var name = element.SelectSingleNode("name").InnerText;
    var product = new Product(id, name);
    //Console.WriteLine($"Id: {id}, name: {name}");

    products.Add(product);

} // Close your loop here!!

using (var writer = new StreamWriter("C:\\Users\\Saint\\Desktop\\TaskRetail\\file.csv", false, Encoding.UTF8))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    csv.WriteRecords(products);
}

Upvotes: 1

Related Questions