2012-06-27 52 views
2

我想分組一些數據沒有太多的運氣。LINQ組條件後跟日期組

我有數據列表

public class TransactionsViewModel 
{ 
    public string BusinessName { get; set; } 
    public string Description { get; set; } 
    public int TransactionTypeId { get; set; } 
    public string TransactionType { get; set; } 

    [Display(Name = "Transaction Amount")] 
    public decimal TransactionAmount { get; set; } 

    [Display(Name = "Transaction Date")] 
    public DateTime TransactionDateTime { get; set; } 

} 

我想要做一些這方面的分組所以我創建像

public class BusinessTransaction 
{ 
    public string Name { get; set; } 
    public List<Transaction> Transactions { get; set; } 
} 

public class Transaction 
{ 
    public decimal TransactionAmount { get; set; } 
    public string Description { get; set; } 
    public DateTime TransactionDate { get; set; } 
    public string TransactionType { get; set; } 

} 

這樣我就可以組幾個類由BUSINESSNAME說起來很簡單

var data = from c in transactions 
        group c by c.BusinessName 
        into business 
        select new BusinessTransaction() 
           { 
            Name = business.Key, 



           }; 

如何通過TransactionDateTime.Date對交易進行分組?我想發送回客戶端的數據結構像

BusinessName 
    28-06-12 
    Transaction 
    Transaction 
    27-06-12 
    Transaction 
BusinessName 
    28-06-12 
     Transaction 
+0

考慮更改 '名單交易{獲得;組; }' 至 'IEnumerable > Transactions {get;組; }' – pnvn

回答

1

我想你想要的東西,如:

var data = from c in transactions 
      group c by c.BusinessName 
      into business 
      select new BusinessTransaction 
      { 
       Name = business.Key, 
       Transactions = business.OrderBy(t => t.TransactionDateTime) 
             .ToList() 
      }; 

編輯:這就是您可以與您當前BusinessTransaction類支持結構。如果您想直接支持分組,則必須在其中添加另一層嵌套。

然而,使用現有的結構,客戶端可以隨時組事物本身:

foreach (var business in query) 
{ 
    Console.WriteLine(business.Name); 
    foreach (var group in business.Transactions 
            .GroupBy(t => t.TransactionDateTime.Date)) 
    { 
     Console.WriteLine(" {0}", group.Key); 
     foreach (var transaction in group) 
     { 
      Console.WriteLine(" {0}", transaction.Description); 
     } 
    } 
} 
+0

OP要按商業名稱*和*按日期分組... –

+0

@ThomasLevesque:啊 - 我不確定當我開始回答問題時,這個例子是否存在。我已編輯,以顯示如何完成,排序... –

+0

謝謝@Jon Skeet。我把數據作爲json發送給客戶端,所以我不能使用linq。我將創建另一個課程和小組 –