C#Linq Group问题,可能真的很容易!

时间:2009-07-06 17:34:17

标签: c# linq group-by

这是我正在分组的班级:

public class RefundTran : DataObjectBase<RefundTran>
    {
        public string ARTranID { get; set; }
        public decimal Amount { get; set; }
        public string ARTranTypeCode { get; set; }
        public int CheckNumber { get; set; }
        public int CustID { get; set; }
        public string PaymentTypeCode { get; set; }
        public string PostedFlag { get; set; }
        public decimal TaxAmount { get; set; }
        public string TranDate { get; set; }
        public string RefNumber { get; set; }
        public decimal Balance { get; set; }
    }

这是List&lt;&gt;:

    List<RefundTran> trans = batchRefundToProcess.RefundCustomer.ARTransactions;

这是我到目前为止获得的Linq查询:

var TransGroupedByType =
                    from t in trans
                    group t by t.PaymentTypeCode into g
                    select new { CustID = g.First<RefundTran>().CustID, PaymentTypeCode = g.Key, TotalBalance = g.Sum (p=> p.Balance) };

基本上,我想要的是一组以paymentTypeCode和TotalBalance为键的交易,其中包含该支付类型代码的RefundTran对象数组。

我错过了什么?

提前致谢!

2 个答案:

答案 0 :(得分:2)

您似乎也需要一组事务,您应该将其添加到匿名类型:

var TransGroupedByType = from t in trans
                         group t by t.PaymentTypeCode into g
                         select new { 
                            CustID = g.First().CustID, 
                            PaymentTypeCode = g.Key, 
                            TotalBalance = g.Sum(p => p.Balance),
                            TransactionList = g.ToArray()
                         };

答案 1 :(得分:0)

t由t.PaymentTypeCode

组成

考虑将其更改为:

按新{t.PaymentTypeCode,t.TotalBalance}

分组

您希望按两个属性进行分组。然后,您就可以访问g.Key.PaymentTypeCode,g.Key.TotalBalance