C#Dictionary计算组值的总和

时间:2017-08-25 08:50:39

标签: c# .net dictionary

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

结构如下:

Dictionary<myObject, int> items.

基本思想是将项目字典传递给方法。我只在字典中添加了唯一的myObjects。 myObject附加了一个计数器规则。一旦计数器规则完全填满,我想用字典中的所有myObect进行计算。

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;
    }
}

您知道如何解决这个问题,或者您对如何解决这个问题有所了解吗?

非常感谢!!

3 个答案:

答案 0 :(得分:4)

您可以使用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;
}

答案 1 :(得分:2)

使用Linq

//check if yourDictonary is not null
var sum = yourDictonary.Select(x => x.Key.Discount.Count == x.Value).Sum(x => x.Value) 

答案 2 :(得分:0)

如果我理解了问题,也许可以这样做

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

return __totalDiscount;