linq group by condition,后跟一个日期组

时间:2012-06-27 22:00:28

标签: c# 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

1 个答案:

答案 0 :(得分: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);
        }
    }
}