Home > Blockchain >  get value in ObserableColection<> and process it?
get value in ObserableColection<> and process it?

Time:11-16

Im new Linq in c# . I have a problem that needs to be solved. I add the values ​​to the ObserableColection. where there is count and price and i want to take those 2 values ​​and add it and write it in the function. Can anyone help me please.

my code :

public CookViewModel()
{
    cookviewmodel = new ObservableCollection<CookModel>();
    cookviewmodel.Add(new CookModel { Menu = "Bắp bò ngâm mắm nhĩ", PriceMenu = Utils.ConvertMoney("1000000"), Count = 2, DoStatus = "Hoàn tất", SumMoney = Sum() });
    cookviewmodel.Add(new CookModel { Menu = "Bắp bò ngâm mắm nhĩ", PriceMenu = Utils.ConvertMoney("1000000"), Count = 1, DoStatus = "Hoàn tất" });
    cookviewmodel.Add(new CookModel { Menu = "Bắp bò ngâm mắm nhĩ", PriceMenu = Utils.ConvertMoney("1000000"), Count = 1, DoStatus = "Hoàn tất" });
}

public double Sum()
{
    var count  = from f in cookviewmodel
                        select f.Count;
    var price = from p in cookviewmodel
                       select p.PriceMenu;
    
    return Convert.ToInt32(count) * Convert.ToDouble(count); 
}

I need to get the value of Count and PriceMenu and add them together

Class Utils :

class Utils
{
     public static string ConvertMoney(string value)
     {
         CultureInfo cul = CultureInfo.GetCultureInfo("vi-VN");
         return double.Parse(value).ToString("#,###", cul.NumberFormat); 
     }
}

CodePudding user response:

I would do like this

internal class CookModel
{
    public string Menu { get; set; }
    public double PriceMenu { get; set; }
    public double  Count { get; set; }
    public double SumMoney => Count * PriceMenu;
}

CodePudding user response:

First, change your PriceMenu variable to be of numerical value (e.g. double) and not text (string), then you can use Select operator to map 'price multiplied by count';

totalCost = cookviewmodel.Select(vm => vm.Count * vm.PriceMenu).Sum()

ps. Maybe "ordersReceived" is a better variable name then "cookviewmodel" ?

  • Related