如何编写Foreach以获得与查询相同的结果?

时间:2019-04-10 06:53:39

标签: c# entity-framework foreach

我有这样的代码:

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循环获得它。有可能吗?

3 个答案:

答案 0 :(得分:4)

您可以将 projection 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);
}

答案 1 :(得分:0)

您可以使用foreach之类的

df1.join(df2, "field");

我的结构完整性

        List<item> query = new List<item>();
        List<itemDto> test = new List<itemDto>();

        // either use this or the next method where mapping is done seperately
        query.ForEach(q => test.Add(new itemDto {id= q.id, type= q.type }));

        // Where the convert method is your conversion code
        // you can use a automapper/reflection to make it more generic
        query.ForEach(q => test.Add(Convert(q)));

答案 2 :(得分:0)

由于性能问题,我建议使用for循环,而不要使用foreach或linq。 For循环永远比所有循环都快。