简体   繁体   中英

How to add new data to the existing in Dictionary?

There is a dictionary, what contains already some data. How to add new data to already exist? And all methods have to me made separately, as I will call them in switch.

public class Product
{
    public static Dictionary<string, decimal> ProductStore()
    {
        return new Dictionary<string, decimal>()
                {
                    { "Apple Juice", 2.5M },
                    { "Pizza", 16.7M },
                    { "Cheese Cake", 4.5M },
                };
    }               

    public static void CheckProductList()
    {
        foreach (var kvp in ProductStore())
            Console.WriteLine("Product name: {0}, Price: {1}", kvp.Key, kvp.Value);
    }

    public static void AddProduct()
    {
        string ProductName = Console.ReadLine();
        decimal ProductPrice = decimal.Parse(Console.ReadLine());
        ProductStore()[ProductName] = ProductPrice;
    }
}

The problem is that, new dictionary always returns some data?

You should keep your dictionary and instantiate it only one time. For example it's possible with private backing field. Also on adding data you should check if the data with the given key is exists, then you should update the value.

public  static class Product
{
    private static readonly Dictionary<string, decimal> ProductStore = new Dictionary<string, decimal>()
    {
        { "Apple Juice", 2.5M },
        { "Pizza", 16.7M },
        { "Cheese Cake", 4.5M },
    };
    
    public static Dictionary<string, decimal> GetProductStore()
    {
        return ProductStore;
    }               

    public static void CheckProductList()
    {
        foreach (var kvp in ProductStore)
            Console.WriteLine("Product name: {0}, Price: {1}", kvp.Key, kvp.Value);
    }

    public static void AddProduct()
    {
        string ProductName = Console.ReadLine();
        decimal ProductPrice = decimal.Parse(Console.ReadLine());
        if (!ProductStore.TryAdd(ProductName, ProductPrice))
            ProductStore[ProductName] = ProductPrice;
    }
}

I think all you want is making the Dictionary a field/property (rather than creating it fresh every time). That way the values are remembered.

using System;
using System.Collections.Generic;

public class ProductRepository
{
    private readonly Dictionary<string, decimal> _products;
    
    public ProductRepository()
    {
        _products = new Dictionary<string, decimal>()
                        {
                            { "Apple Juice", 2.5M },
                            { "Pizza", 16.7M },
                            { "Cheese Cake", 4.5M },
                        };
    }
    
    public IReadOnlyDictionary<string, decimal> Products => _products;

    public void AddOrUpdateProduct(string productName, decimal price)
    {
        _products[productName] = price;
    }
}

public static class Program
{
    public static void Main()
    {
        var productRepository = new ProductRepository();
        PrintAllProducts(productRepository);
        Console.WriteLine("Now add a new product by giving the name and price.");
        var newProductName = Console.ReadLine();
        var newProductPrice = decimal.Parse(Console.ReadLine());
        productRepository.AddOrUpdateProduct(newProductName, newProductPrice);
        PrintAllProducts(productRepository);
        Console.WriteLine("Press enter to exit.");
        Console.ReadLine();
    }
    
    private static void PrintAllProducts(ProductRepository productRepository)
    {
        foreach (var (productName, price) in productRepository.Products)
        {
            Console.WriteLine($"Product {productName} costs {price}.");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM