Search code examples
c#listwcfrecordcontract

C# print list issue


I'm doing a WCF service with GUI as client, however I have a problem with printing list of current items added. I have a code to add new entries to the list:

    public bool Add_Data(Data sample)
    {
        container.Add(sample);
        Console.WriteLine("New record added!");
        return true;
    }

And it's working, however when I'm trying to view added records with first try it works, however if I want to view it again list is adding same element. To show you how it works:

  1. I'm adding new entry and I "print" list: IMAGE CLICK [works how it should]
  2. However I want to see it again, so I'm pressing same button in my form, and here is what happens:IMAGE CLICK as you can see, we have our list + additional same record, if I will press button again, I will have 3 same records.

Here is my "show records" code:

   public string Show_Data()
    {
        Console.WriteLine("Printing records");
        foreach (Data record in container)
        {
            string final_result = ("\nID: "+  + record.ID + " " + "product: " + record.product + " " + "category: " + record.category + " " + "price: " + record.price + " " + "quantity: " + record.quantity + " " + "\n ");
            result += final_result;
        }
        return result;                  
    }

Let me know if you know how to solve it.


Solution

  • You need to look into variable scope. You have result declared outside of the Show_Data() method. Each time the method is called you are doing result += final_result; which is adding to result. Try the code below and you will get different results.

    public string Show_Data()
    {
        Console.WriteLine("Printing records");
        var output = string.Empty;
        foreach (Data record in container)
        {
            string final_result = ("\nID: "+  + record.ID + " " + "product: " + record.product + " " + "category: " + record.category + " " + "price: " + record.price + " " + "quantity: " + record.quantity + " " + "\n ");
            output += final_result;
        }
        return output;                  
    }
    

    Also, I would consider using a string builder and string format as well.

    public string Show_Data()
    {
        Console.WriteLine("Printing records");
        var output = new StringBuilder();
        foreach (Data record in container)
        {
            string final_result = string.Format("ID: {0} product: {1} category: {2} price: {3} quantity: {4}", record.ID, record.product, record.category, record.price, record.quantity);
    
            // if using C# 6
            // string final_result = string.Format($"ID: {record.ID} product: {record.product} category: {record.category} price: {record.price} quantity: {record.quantity)}";
            output.AppendLine(final_result);
        }
        return output.ToString();                  
    }