【问题标题】:Grouping duplicate items in a list, and adding their totals将列表中的重复项目分组,并添加它们的总数
【发布时间】:2013-03-19 03:12:33
【问题描述】:

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

我正在检查重复项的属性是 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;
    }

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

【问题讨论】:

  • 你如何定义“重复”?

标签: c# duplicates


【解决方案1】:

如果我理解正确的话:

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

希望对你有帮助

【讨论】:

  • 做了我想做的事,谢谢!
【解决方案2】:
A.Intersect(B).Count;

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

class ShoppingCartDTO : IEquatable<ShoppingCartDTO>
{
}

【讨论】:

    【解决方案3】:

    旧式解决方案,类似。

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

    【讨论】:

      【解决方案4】:

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

      var results = shoppingList.GroupBy(s => s.ProductID)
                                .Select(g => new {
                                                     ProductID = g.Key,
                                                     totalQty = g.Sum(I => i.Quantity)
                                                 }
                                       );
      

      【讨论】:

        【解决方案5】:

        你可以这样做:

        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 值将被求和。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-06-03
          • 2013-10-01
          • 1970-01-01
          • 2020-06-01
          • 2020-02-08
          • 2020-05-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多