删除重复项并汇总列表中的金额

时间:2019-12-22 19:41:13

标签: c# asp.net linq

我有一个 r.Method = "POST" r.ParseForm() ,其中包含一些重复的值

示例:

List<order>

我希望这样:

product price amount
Coke     4     1
Coke     4     1
Sprite   4     1

以便合并重复项并计算金额值

我有此代码,但无法正常工作:

product price amount
Coke     4     2
Sprite   4     1

我要从List<Order> values; values = ((List<Order>)Session["Cart"]).GroupBy(x => new { x.product, x.price}) .Select(x => new Order(x.Key.product, x.Key.price, x.Sum(y => y.amount))) .ToList(); 的上一页中获取值

1 个答案:

答案 0 :(得分:0)

很明显,问题发生在((List)Session [“ Cart”])

因为我尝试了以下模型和数据

public class Order
{
    public Order(string product, int price, int amount)
    {
        this.product = product;
        this.price = price;
        this.amount = amount;
    }
    public string product { get; set; }
    public int price { get; set; }
    public int amount { get; set; }
}

var list = new List<Order>() { new Order("Coke",4,1), new Order("Coke",4,1), new Order("Sprite",4,1)};

您的查询可以正常运行

var result = list.GroupBy(x => new { x.product, x.price})
              .Select(x => new Order(x.Key.product, x.Key.price, x.Sum(y => y.amount)))
              .ToList(); 

此问题可能是由于显式转换会话[“购物车”] 的类型或为空