使用groupby计算列的和

本文关键字:计算 groupby 使用 | 更新日期: 2023-09-27 18:11:30

我正在尝试使用groupby计算我的客户债务

我有两个表的结构,你可以在这里看到:

  public partial class Inovice
    {
        public Inovice()
        {
            this.Payments = new HashSet<Payment>();
            this.InvoiceDetails = new HashSet<InvoiceDetail>();
        }
        public PersianCalendar objPersianCalender = new PersianCalendar();
        [DisplayName("شناسه")]
        public int Id { get; set; }
        [DisplayName("شناسه کاربر")]
        public int MemberId { get; set; }
        public virtual ICollection<InvoiceDetail> InvoiceDetails { get; set; }
    }

这个表保存客户发票,另一个表保存客户购买的商品。结构如下:

 public partial class InvoiceDetail
    {
        [DisplayName("شناسه ")]
        public int Id { get; set; }

        [DisplayName("مقدار")]
        public Nullable<double> Amount { get; set; }   
        [DisplayName("شناسه فاکتور")]
        public int InoviceId { get; set; }
        public Nullable<bool> IsReturned { get; set; }
        public virtual Inovice Inovice { get; set; }
    }

我的价值观:

MemberOrCustomer       sumOfAmountvalues
1                        12
1                        8
2                        12
2                        11

这两个表在invoiceid上有关系,我需要对每个memberId(Invoice)amount(InvoiceDetail)值求和,例如:

MemberOrCustomer       sumOfAmountvalues
1                        20
2                        23

我写了这段代码来做这个,但是它不起作用:

 var result= invoices.GroupBy(i => i.MemberId).Select(group=>new {Amount=group.Sum(Amount)} );

使用groupby计算列的和

您可以使用invoicesDetails列表。

var result = invoicesDetails.GroupBy(id => id.Invoice.MemberId)
                            .Select(g => new {
                                       MemberOrCustomer = g.Key,
                                       Amount = g.Sum(x => x.Amount)
                            });

其中invoiceDetails可能是

invoices.SelectMany(x => x.InvoiceDetails)

invoices
    .SelectMany(x => x.InvoiceDetails)
    .GroupBy(id => id.Invoice.MemberId)
    .Select(g => new {
               MemberOrCustomer = g.Key,
               Amount = g.Sum(x => x.Amount)
    });