2017-08-25 222 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