2012-02-07 68 views
0

多列我有一個包含字段一個DataTable:的LINQ to SQL檢索一個DataTable,包括分組和總和

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

我想在LINQ以下SQL相當於實現:

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

我已經試過如下:

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

這工作,但只返回TransactionID和指定事務中的記錄數。我應該如何修改我的LINQ以包括TransactionDate和總和(AdjustedValue)字段?

public int BatchID {get; set;} 
public DateTime TransactionDate {get; set;} 
public int ItemCount {get; set;} 
public decimal TotalValue {get; set;} 

回答

1

您需要創建一個匿名類型的組獲得多個值:作爲

TransactionIDListItem類中定義。

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

現在在你的選擇,你只需要添加新的值。 g.Key是您的匿名類型,因此它具有您分組的屬性。

select new TransactionIDListItem 
      { 
       TransactionID = g.Key.TransactionID, 
       TransactionDate = g.Key.TransactionDate, 
       TotalValue = g.Sum(x => x.AdjustedValue) 
       ItemCount = g.Count() 
      }).ToList(); 
+0

這就是我所缺少的。謝謝!對於它的價值,我還需要將我的「order by g.key」更改爲「order by g.Key.TransactionID」以減輕「至少有一個對象必須實現IComparable」錯誤。感謝Lisa Zoglio Morgan [鏈接](http://stackoverflow.com/questions/6467272/at-least-one-object-must-implement-icomparable) – user1156862 2012-02-07 21:46:48