gpt4 book ai didi

c# - linq 按条件分组后跟日期组

转载 作者:太空宇宙 更新时间:2023-11-03 13:58:57 25 4
gpt4 key购买 nike

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

我有一个数据列表

 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

最佳答案

我想你想要这样的东西:

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

关于c# - linq 按条件分组后跟日期组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11235397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com