0

I've got a single datatable that contains the fields:

TransactionID (int),
TransactionDate (DateTime)
AdjustedValue (decimal)

I'd like to achieve in LINQ the equivalent of the following SQL:

SELECT TransactionID, TransactionDate, Sum(AdjustedValue), COUNT(*) AS ItemCount 
FROM DATATABLE 
WHERE TransactionDate >= BeginDate 
    and TransacationDate < EndDate 
GROUP BY TransactionID 
ORDER BY TransactionID DESCENDING

I've tried the following:

var query = (from lui in DTbatches.AsEnumerable()
             where lui.TransactionDate >= BeginDate &&
             lui.TransactionDate < EndDate
             group lui.TransactionID by lui.TransactionID into g
             order by g.Key descending
             select new TransactionIDListItem
             {
                  TransactionID = g.Key,
                  ItemCount = g.Count()
             }).ToList();

This works, but only returns the TransactionID and the count of records in the specified transaction. How should I modify my LINQ to also include the TransactionDate and the sum(AdjustedValue) fields?

My TransactionIDListItem class is defined as:

public int BatchID {get; set;}
public DateTime TransactionDate {get; set;}
public int ItemCount {get; set;}
public decimal TotalValue {get; set;}
cadrell0
  • 17,109
  • 5
  • 51
  • 69

1 Answers1

1

You need to create an anonymous type for your group to get multiple values.

group lui by new 
                 {
                     lui.TransactionID,
                     lui.TransactionDate
                 }
    into g

Now in your select, you just need to add the new values. g.Key is your anonymous type, so it has the properties you grouped by.

select new TransactionIDListItem
           {
               TransactionID = g.Key.TransactionID,
               TransactionDate = g.Key.TransactionDate,
               TotalValue = g.Sum(x => x.AdjustedValue)
               ItemCount = g.Count()
           }).ToList();
cadrell0
  • 17,109
  • 5
  • 51
  • 69
  • that was what I was missing. Thank you! For what it's worth, I also needed to change my "orderby g.key" to "orderby g.Key.TransactionID" to alleviate an "At least one object must implement IComparable" error. Thanks to Lisa Zoglio Morgan [link](http://stackoverflow.com/questions/6467272/at-least-one-object-must-implement-icomparable) – user1156862 Feb 07 '12 at 21:46