Update a List item class (shopping basket)

Hello guys
I am just playing around with the List generic class and stuck with updating the hard coded list items. Here is my class and code

I want to update the dynamically chosen item in the console prompt with the quanity entered

Products.Products item = Prods.Find(c => c.Name == x);
var hello = Prods.Find(c => c.Name == x);

But the linq function returns null at runtime

List<Products.Products> Prods = new List<Products.Products>();
Products.Products Prod = new Products.Products();
Prod.Name = “Cakes”;
Prod.price = 0.50;
Prods.Add(Prod);

        Prod.Name = "Bread";
        Prod.price = 1.50;
        Prods.Add(Prod);

        Prod.Name = "Loaf";
        Prod.price = 2.50;
        Prods.Add(Prod);
        Console.WriteLine("What item do you want ? ");
       var x = Console.ReadLine();
        Console.WriteLine("Please enter the quantity");
        var q = Console.ReadLine();

Products.Products item = Prods.Find(c => c.Name == x);
var hello = Prods.Find(c => c.Name == x);
Prod.Name = x;
Prod.price = 0.50;
Prod.quantity = int.Parse(q);
Prods.Add(Prod);

        Console.WriteLine("You have entered {0} as your chosen product and {1} price and {2} quanity", x, Prod.total , q);
    }

public class Products
{
public string Name { get; set; }
public double price { get; set; }

    public int quantity { get; set; }
    public double total { get { return price * quantity; } }

    
}

I found the answer here

      var getPrice = Prods.FirstOrDefault(d => d.Name == x);
        if (getPrice != null) { getPrice.quantity = int.Parse(q); }
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.