Chris McCall
Chris McCall

Reputation: 10407

C# Linq Group By issue, probably really easy!

Here's my Class that I'm grouping:

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

Here's the List<>:

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

And here's the Linq query I've got so far:

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

Basically, what I want is a group of transactions, keyed on both paymentTypeCode and TotalBalance, containing an array of RefundTran objects for that payment type code.

What am I missing?

Thanks in advance!

Upvotes: 1

Views: 2449

Answers (2)

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422112

It seems you want an array of transactions too, you should add it to the anonymous type:

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

Upvotes: 2

David Hedlund
David Hedlund

Reputation: 129802

group t by t.PaymentTypeCode

consider changing that to:

group t by new { t.PaymentTypeCode, t.TotalBalance }

it you want to group by both properties. You'll then be able to access g.Key.PaymentTypeCode, g.Key.TotalBalance

Upvotes: 0

Related Questions