1

您好,我有一个列表,我正在尝试对重复项进行分组并添加它们的数量以将其与最大数量进行比较。我遇到的唯一问题是隔离重复项并添加它们的数量。我陷入了精神障碍,无法找出正确的方法来实现我正在尝试的目标。所以我希望有人能够指出我正确的方向并帮助我摆脱困境!

我正在检查重复项的属性是 ProductID

double qty = 0;
double totalQty = 0;
bool isQtyValid = true;

List<ShoppingCartDTO> shoppingList = ShoppingCart.Fetch(string.Format("WHERE SessionID='{0}'", Session["ID"]));
    foreach (ShoppingCartDTO temp in shoppingList)
    {
        qty =  temp.Quantity;
        totalQty += qty;
        isQtyValid = getCheckQty(totalQty, temp.ProuductID, temp.CustomerID);
        CheckOut.Enabled = isQtyValid;
        lblError.Visible = !isQtyValid;
    }

如果可以进行更多解释,我可以尝试更好地解释,并在需要时提供更多代码。我感谢任何人的建议和帮助。谢谢!

4

5 回答 5

0
A.Intersect(B).Count;

这能找出重复的项目数吗?您还可以为 ShoppingCartDTO 类实现 IEquatable 接口:

class ShoppingCartDTO : IEquatable<ShoppingCartDTO>
{
}
于 2013-03-28T15:38:43.737 回答
0

如果我理解正确:

var groupedList = shoppingList.GroupBy( item => item.[the property you want to group by on]);

foreach (var g in groupedList)
{
   var sum = g.Sum( i => i.[the property you want to sum]);
}

希望能帮助到你

于 2013-03-28T15:43:54.447 回答
0

旧式解决方案,类似于。

List<ShoppingCartDTO> shoppingList = ShoppingCart.Fetch(string.Format("WHERE SessionID='{0}'", Session["ID"]));
    Dictionary<String, Double> groups = new Dictionary<String,Double>();
    foreach (ShoppingCartDTO temp in shoppingList)
    {
        String key = String.Format("{0}-{1}", temp.CustomnerID, temp.ProductID); 
        if (groups.ContainsKey(key))
        {
           groups[key] += temp.Quantity;
        }
        else
        {
           groups.Add(key, temp.Quantity);
        }
    }
于 2013-03-28T15:48:03.140 回答
0

假设有一些属性定义了您的“重复”,例如ProductId

var results = shoppingList.GroupBy(s => s.ProductID)
                          .Select(g => new {
                                               ProductID = g.Key,
                                               totalQty = g.Sum(I => i.Quantity)
                                           }
                                 );
于 2013-03-28T15:48:12.860 回答
0

你可以这样做:

var groups = shoppingList.GroupBy(e => e.ProductId).ToList();
shoppingList.Clear();
foreach (var group in groups)
{
    group.First().Quantity = group.Sum(e => e.Quantity);
    shoppingList.Add(group.First());
}

运行后,shoppingList应该不包含重复项,并且Quantity所有重复项的值都将相加。

于 2013-03-28T15:48:51.707 回答