我目前正在使用 C# 开发一个应用程序。想象一下带有收银台的店面。我有一个字典结构,其中一个对象作为键,一个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) 我填写项目字典并将其传递给处理程序方法:
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 循环访问 Dictionary,如下所示:
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# 字典计算组值的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45877707/