2017-08-25 126 views
1

我目前正在使用C#编写应用程序。想象一下带有结帐的店面。我有一个对象作为键int对象计数器作为值字典结构。C#字典计算组值的总和

的结构是这样的:

Dictionary<myObject, int> 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)我填的项目字典,并把它传递给处理方法:

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

你知道如何解决这个问题,或者你有如何解决这个问题的想法?

非常感谢!

+0

_totalDiscountedValue = _totalDiscountedValue + _discountHandler.CalculateDiscount(_items); –

回答

3

你可以通过字典使用的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; 
} 
+0

由于使用守卫子句 –

+0

,我更喜欢这个答案你是否介意解释“guard clause”的含义?这个答案与我的有什么不同? – Wndrr

0

如果我正确地理解这个问题,也许这样做会工作

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

return __totalDiscount; 
+0

'Key.Dicount'应该是'Key.Discount',OP具有相同的拼写错误,并且为了检查if语句中的等式,使用'=='而不是'='。句法! ;) –

+0

哦,我的坏!在给出答案之前,我绝对应该测试运行我的代码,“=”不好!谢谢你<3 – Wndrr

1

使用LINQ

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

很好用的Linq!我不知道总和的方法,谢谢你:-) – Wndrr

+0

感谢upvote ;-) – Winnie