2

我正在尝试对一些数据进行分组,但运气不佳。

我有一个数据列表

 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
4

1 回答 1

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);
        }
    }
}
于 2012-06-27T22:02:56.280 回答