Need help about List<T>

Jerry Lipan 916 Reputation points
2022-04-14T03:24:12.037+00:00

Hi,

I've class as following,

Product.cs

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
  
namespace Training12042022.ViewModels  
{  
    public class Product  
    {  
        public int Id { get; set; }  
        public string Title { get; set; }  
        public string UrlImage { get; set; }  
        public string Detail { get; set; }  
        public decimal Price { get; set; }  
  
    }  
  
  
}  
  

Cart.cs

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
  
namespace Training12042022.ViewModels  
{  
    public class Cart  
    {  
        public Product Product { get; set; }  
        public int Quantity { get; set; }  
    }  
}  
  

I don't know how to access item in List<Cart>. Need help

So far, I've this

public IActionResult Index()  
        {  
            var _Product = _contextECommerceDB.Product.ToList();  
            ViewBag.Product = _Product;  
  
            var cart = HttpContext.Session.GetString("cart");//get key cart  
            if (cart != null)  
            {  
                List<Cart> dataCart = JsonConvert.DeserializeObject<List<Cart>>(cart);  
  
                if (dataCart.Count == 1)  
                {  
                    ViewBag.NoOfCart = dataCart.Count.ToString() + " product";  
                }  
                else   
                {  
                    ViewBag.NoOfCart = dataCart.Count.ToString() + " products";  
                }  
  
            }  
            else  
            {  
                ViewBag.NoOfCart = "0 product";  
            }  
  
  
            return View();  
        }  

192913-14042022-003.png

192914-14042022-004.png

How to access data

  1. Product(Id)
  2. Product(Title)
  3. Quantity

And so on ?

Please help

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,383 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,627 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,096 Reputation points Microsoft Vendor
    2022-04-14T06:07:51.987+00:00

    Hi @Jerry Lipan ,

    How to access data
    Product(Id)
    Product(Title)
    Quantity
    And so on ?

    To access the Product from the Cart, you could use foreach or for loop statement to loop through the list, then access the value from the navigation property (the Product property in the Cart class).

    Refer the following code:

    Controller:

        public IActionResult CartIndex()  
        {  
            //get the cart data:  
            List<Cart> datacart = _datarepo.GetCarts();  
    
            //use foreach or for statement to loop the list  
            foreach (var item in datacart)  
            {  
                Console.WriteLine("Product Id: {0} Product Title: {1} Quantity: {2}", item.Product.Id, item.Product.Title, item.Quantity.ToString());  
            }  
    
            return View(datacart);  
        }  
    

    If you want to access the value in the view page, the code like this:

    [Note] In the View page, if you want to list and update the value first, and then submit the updated the value to the controller, in this scenario, you'd better use for loop statement to display the page model data.

    @model IEnumerable<MVCWebApp.Models.Cart>  
      
    @{  
        ViewData["Title"] = "CartIndex";  
    }  
      
    <table class="table">  
        <thead>  
            <tr>  
                <th>Product Id</th>  
                <th>Product Title</th>  
                <th>  
                    @Html.DisplayNameFor(model => model.Quantity)  
                </th>  
                <th></th>  
            </tr>  
        </thead>  
        <tbody>  
    @foreach (var item in Model) {  
            <tr>  
                <td>  
                     @Html.DisplayFor(modelItem => item.Product.Id)  
                </td>  
                <td>  
                     @Html.DisplayFor(modelItem => item.Product.Title)  
                </td>  
                <td>  
                    @Html.DisplayFor(modelItem => item.Quantity)  
                </td>  
                <td>  
                    @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |  
                    @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |  
                    @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })  
                </td>  
            </tr>  
    }  
        </tbody>  
    </table>  
    

    The output like this:

    192993-1.gif


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    1 person found this answer helpful.
    0 comments No comments

4 additional answers

Sort by: Most helpful
  1. Sudipta Chakraborty - MSFT 1,106 Reputation points Microsoft Employee
    2022-04-14T04:49:18.927+00:00

    @Jerry Lipan :

    You can cast the List to an array and then use a for loop to iterate over the List and get the respective details of the object Product.

    for(int i=0;i<dataCart.Count;i++)  
    {  
       var productId  = dataCart.ToArray()[i].Product.Id;  
       var productDetail  = dataCart.ToArray()[i].Product.Detail;  
    }  
    
    0 comments No comments

  2. Jerry Lipan 916 Reputation points
    2022-04-14T08:06:16.877+00:00

    Hi @Sudipta Chakraborty - MSFT , Hi @Zhi Lv - MSFT

    I'm still confuse. How to sum ( Quantity ) ? Some Product have Quantity = 1. Some Product, Quantity = 2. See this data,

    192870-14042022-006.png

    193015-14042022-007.png

    193042-14042022-008.png

    json data as following,

    [{"Product":{"Id":1,"Title":"Spider-Man: No Way Home","UrlImage":"1.png","Detail":"xxxxxx","Price":103.50},"Quantity":2},{"Product":{"Id":3,"Title":"Shang-Chi: Legend Of The Ten Rings","UrlImage":"3.png","Detail":"zzzzzz","Price":102.40},"Quantity":1},{"Product":{"Id":2,"Title":"The Eternals","UrlImage":"2.png","Detail":"yyyyyy","Price":102.40},"Quantity":1}]  
    

    I want to sum ( Quantity )

    Please help

    0 comments No comments

  3. Karen Payne MVP 35,386 Reputation points
    2022-04-14T09:53:57.403+00:00

    First off, this does not make sense, one product which means Quantity is always going to be 1

    public class Cart  
    {  
        public Product Product { get; set; }  
        public int Quantity { get; set; }  
    }  
    

    Should be

    public class Cart  
    {  
        public List<Product> Products { get; set; }  
        public int Quantity { get; set; }  
    }  
    

    But I'll stay with what you presented in a small example excluding some properties done in a unit test.

    public class Product  
    {  
        public int Id { get; set; }  
        public string Title { get; set; }  
        public decimal Price { get; set; }  
    }  
      
    public class Cart  
    {  
        public Product Product { get; set; }  
        public int Quantity { get; set; }  
    }  
      
    public class DataOperations  
    {  
        private static string _FileName = Path.Combine(  
            AppDomain.CurrentDomain.BaseDirectory, "carts.json");  
      
        public static void CreateCart()  
        {  
            List<Cart> cartList = new List<Cart>();  
      
            Cart cart1 = new()  
            {  
                Quantity = 1,  
                Product = new Product  
                {  
                    Id = 9,  
                    Title = "Chai tea",  
                    Price = 18m  
                }  
            };  
      
      
            Cart cart2 = new()  
            {  
                Quantity = 1,  
                Product = new Product  
                {  
                    Id = 24,  
                    Title = "Irish tea",  
                    Price = 4m  
                }  
            };  
      
            cartList.AddRange(new[] { cart1, cart2 });  
      
            var json = JsonConvert.SerializeObject(cartList, Formatting.Indented);  
            File.WriteAllText(_FileName, json);  
        }  
      
        public static List<Cart> GetCarts() =>   
            JsonConvert.DeserializeObject<List<Cart>>(File.ReadAllText(_FileName));  
    }  
    

    Run the above

    [TestMethod]  
    [TestTraits(Trait.PlaceHolder)]  
    public void TestMethod1()  
    {  
          
      
        DataOperations.CreateCart();  
      
        var dataCart = DataOperations.GetCarts();  
      
        Console.WriteLine($"Count: {dataCart.Count}");  
      
        foreach (var cart in dataCart)  
        {  
            Console.WriteLine($"{cart.Product.Id,-3}{cart.Product.Title,-15}{cart.Product.Price:C}");  
        }  
      
        Console.WriteLine($"Total: {dataCart.Sum(x => x.Product.Price):C}");  
          
    }  
    

    193106-f1.png

    0 comments No comments

  4. Jerry Lipan 916 Reputation points
    2022-04-15T01:01:18.063+00:00

    Thanks to all. My problem has been solved

    0 comments No comments