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;}
You need to create an anonymous type for your group to get multiple values.
Now in your select, you just need to add the new values.
g.Keyis your anonymous type, so it has the properties you grouped by.