C# 如何编写Foreach以获得与查询相同的结果?
我有这样一个代码:C# 如何编写Foreach以获得与查询相同的结果?,c#,entity-framework,foreach,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;
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结合使用,它可能更简洁一些
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();
或
可以将投影与Linq结合使用,它可能更简洁一些
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();
或
你可以像这样使用foreach
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)));
你可以像这样使用foreach
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)));
出于性能考虑,我建议使用for循环,而不是使用foreach或linq。For循环总是比所有循环都快。出于性能考虑,我建议使用For循环而不是使用foreach或linq。For循环总是比所有循环都快。为什么要投影?我只是想把它改写一下foreach@AliEshghi它在处理db IQueriable时有其优势,而且代码行数较少。但是我更新了一个foreachwhy投影?我只是想把它改写一下foreach@AliEshghi它在处理db IQueriable时有其优势,而且代码行数较少。但是我已经用foreach更新了为什么需要确保构造函数?您还可以将新的itemDto{id=q.id,type=q.type}。也许jfyi:你应该用大写字母写类名和属性——这是一个指导原则。@MatthiasBurger知道我忘了什么!更新、商定的指导原则…只是无法跟进样本为什么需要确保构造函数?您还可以将新的itemDto{id=q.id,type=q.type}。也许jfyi:你应该用大写字母写类名和属性——这是一个指导原则。@MatthiasBurger知道我忘了什么!更新的、商定的指南……只是无法跟进样本