C# 字典 计算组值的总和



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

结构如下所示:

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 遍历字典,如下所示:

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

使用 Linq

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

如果我正确理解了这个问题,也许这样做会起作用

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

最新更新