我有这样的代码:

List<BankDepositHistoryDTO> BankDepositHistoryDTOs = new List<BankDepositHistoryDTO>();

for (int i = 0; i < query.Count; i++)
{
   BankDepositHistoryDTO b = new BankDepositHistoryDTO();

   b.AccountId = query[i].AccountId;
   b.Id = query[i].Id;
   b.Amount = query[i].Amount;
   b.AdditionalData = query[i].AdditionalData;
   b.ClientIp = query[i].ClientIp;
   b.Gateway = query[i].Gateway;
   b.PaymentRefNumber = query[i].PaymentRefNumber;
   b.ReturnUrl = query[i].ReturnUrl;
   b.State = query[i].State;
   b.Uuid = query[i].Uuid;


   BankDepositHistoryDTOs.Add(b);
}


我想知道是否可以通过foreach循环获得它。那可能吗 ?

最佳答案

您可以将投影与Linq Select一起使用,它可能更简洁

var dtos = query.Select(x => new BankDepositHistoryDTO()
                             {
                                AccountId = x.AccountId,
                                Id = x.Id,
                                Amount = x.Amount,
                                AdditionalData = x.AdditionalData,
                                ClientIp = x.ClientIp,
                                Gateway = x.Gateway,
                                PaymentRefNumber = x.PaymentRefNumber,
                                ReturnUrl = x.ReturnUrl,
                                State = x.State,
                                Uuid = x.Uuid
                             }).ToList();


要么

List<BankDepositHistoryDTO> BankDepositHistoryDTOs = new List<BankDepositHistoryDTO>();

foreach(var item in query)
{
   BankDepositHistoryDTO b = new BankDepositHistoryDTO();

   b.AccountId = item.AccountId;
   b.Id = item.Id;
   b.Amount = item.Amount;
   b.AdditionalData = item.AdditionalData;
   b.ClientIp = item.ClientIp;
   b.Gateway = item.Gateway;
   b.PaymentRefNumber = item.PaymentRefNumber;
   b.ReturnUrl = item.ReturnUrl;
   b.State = item.State;
   b.Uuid = item.Uuid;

   BankDepositHistoryDTOs.Add(b);
}

关于c# - 如何编写Foreach以获得与查询相同的结果?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55606425/

10-13 09:15