我目前正在使用C#开发应用程序。想象一下一个结帐的店面。我有一个字典结构,其中一个对象作为Key,一个int对象计数器作为值。

结构看起来像这样:

Dictionary<myObject, int> items.


基本思想是将Items字典传递给方法。我只是将唯一的myObjects添加到字典中。 myObject附加了反规则。一旦反规则已满,我想对字典中的所有myObects进行计算。

myObject看起来像这样:

public class myObject
{
    string ItemId { get; set; }
    Discount Discount { get; set; }
}

 public class Discount
 {
     public int Count { get; set; }
     public decimal Price { get; set; }
     public IDiscountHandler DiscountHandler => new DiscountHandler();
 }


示例myObject可能如下所示:

 var myObectA = new myObject()
 {
     ItemId = "A"
 };

var discountA = new Discount()
{
    Count = 2,
    Price = 12 // special price, if 2 myObjects were added to the Dictionary
};

myObjectA.Discount = discountA;


1)我填写项目Dictionary并将其传递给Handler方法:

private decimal _totalDiscountedValue { get; set; } = 0;

    if (!_items.ContainsKey(myObject))
    {
        _items.Add(myObject, 1);
    }
    else
    {
        _items[myObject]++;
    }

   _totalDiscountedValue += _discountHandler.CalculateDiscount(_items);


2)在我的处理程序中,一旦反规则完全填满,我便尝试对所有折扣值求和。但是不幸的是我在这里挣扎:

public class DiscountHandler : DiscountHandler
{
    private decimal _totalDiscount { get; set; } = 0;

    public override decimal CalculateDiscount(IDictionary<myObject, int> items)
    {
        if (items == null) throw new ArgumentNullException(nameof(items));

        // I'm struggeling here:
        // check if Dictionary[i].Dicount.Count = Dictionary.Value
        // then _totalDiscount += Dictionary[i].Discount.Price

        return _totalDiscount;
    }
}


您知道如何解决此问题,还是对如何解决这个问题有想法?

非常感谢你 !!

最佳答案

您可以使用foreach遍历字典,如下所示:

public override decimal CalculateDiscount(IDictionary<myObject, int> items)
{
    if (items == null) throw new ArgumentNullException(nameof(items));

    foreach (var kvp in items)
    {
        if (kvp.Key.Discount.Count == kvp.Value)
            _totalDiscount += kvp.Key.Discount.Price;
    }
    return _totalDiscount;
}

关于c# - C#词典计算组值的总和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45877707/

10-11 23:01
查看更多