Home

C# DataModel Basic Example

The Code.

using System;
using System.Collections.Generic;
using System.Linq;

namespace CoreApp
{
    class Program
    {
        static void Main(string[] args)
        {
            List<ProductModel> ListOfProducts = new List<ProductModel>();
            ListOfProducts.Add(new ProductModel { ItemName = "Bread", ItemPrice = 0.64M });
            ListOfProducts.Add(new ProductModel { ItemName = "Milk", ItemPrice = 0.65M });
            ListOfProducts.Add(new ProductModel { ItemName = "Peanut Butter", ItemPrice = 1.04M });
            ListOfProducts.Add(new ProductModel { ItemName = "Margerine", ItemPrice = 1.22M });

            CartModel MyCart = new CartModel();
            MyCart.Items = ListOfProducts;

            foreach (ProductModel x in MyCart.Items)
            {
                Console.WriteLine(x.ItemName + " - " + x.ItemPrice);
            }
            Console.WriteLine(MyCart.Total());
        }
    }

    public class ProductModel
    {
        public string ItemName { get; set; }
        public decimal ItemPrice { get; set; }
    }

    public class CartModel
    {
        public List<ProductModel> Items { get; set; } = new List<ProductModel>();
        public decimal Total()
        {
            return Items.Sum(x => x.ItemPrice);
        }
    }
}

The Explanation.

Lets us start in the middle... 

    public class ProductModel
    {
        public string ItemName { get; set; }
        public decimal ItemPrice { get; set; }
    }

We have a class that lets us set a string and a decimal price. 

    public class CartModel
    {
        public List<ProductModel> Items { get; set; } = new List<ProductModel>();
        public decimal Total()
        {
            return Items.Sum(x => x.ItemPrice);
        }
    }

The CartModel is something new to me I'm not used to. Within the model we have a LIST rather than the usual integers and numbers etc. Well why not? Then we have a function Total. Within we are using the "Sum" function on the list. NOTE! You can't use "Sum" on lists without "using System.Linq;". Logic dictates the sum function is part of Linq that extends (gives extra features to) the regular List options like "Add". 

Within the Total function we see a Lambda "x => x.ItemPrice". I am still working on understanding this properly...

Back in the Main function. We create a List of ProductModels then Add to this list be creating a new ProductModel each time. Then we create a CartModel and throw in our List of ProductModels to the Items. Oddly, as if by magic when we ask for the Total we get... the Total straight from the CartModel. 

Reader's Comments

Post Your Comment Posts/Links Rules

Name

Comment

Add a RELEVANT link (not required)

Upload an image (not required)

No uploaded image
Real person number
Please enter the above number below




Home
Admin Ren's Biking Blog