[英]Error Index was out of range. Must be non-negative and less than the size of the collection
I am trying to fill my DTO objects with for, but I got this error: 我想用for填充我的DTO对象,但是我收到了这个错误:
Index was out of range. Must be non-negative and less than the size of the collection
Here is my code: 这是我的代码:
public static List <BankDepositHistoryDTO> DtoTODomain()
{
MyketAdsEntities context = new MyketAdsEntities();
List<BankDepositHistoryDTO> bdto = new List<BankDepositHistoryDTO>();
//var transactionlist
var transactionlist = GetListoftransactions.GetAccountingListoftransactions();
for (int i = 0; i < transactionlist.Count; i++)
{
bdto[i].AccountId = transactionlist[i].AccountId;
bdto[i].Id = transactionlist[i].Id;
bdto[i].Amount = transactionlist[i].Amount;
bdto[i].AdditionalData = transactionlist[i].AdditionalData;
bdto[i].ClientIp = transactionlist[i].ClientIp;
bdto[i].Gateway = transactionlist[i].Gateway;
bdto[i].PaymentRefNumber = transactionlist[i].PaymentRefNumber;
bdto[i].ReturnUrl = transactionlist[i].ReturnUrl;
bdto[i].State = transactionlist[i].State;
bdto[i].Uuid = transactionlist[i].Uuid;
}
return bdto;
}
I got this message at here 我在这里收到了这条消息
bdto[i].AccountId = transactionlist[i].AccountId;
You've created an empty list, and aren't adding elements to it. 您已创建一个空列表,但未向其添加元素。 You must first add an element, and then update its properties: 您必须先添加一个元素,然后更新其属性:
for (int i = 0; i < transactionlist.Count; i++)
{
BankDepositHistoryDTO b = new BankDepositHistoryDTO();
b.AccountId = transactionlist[i].AccountId;
b.Id = transactionlist[i].Id;b
b.Amount = transactionlist[i].Amount;
b.AdditionalData = transactionlist[i].AdditionalData;
b.ClientIp = transactionlist[i].ClientIp;
b.Gateway = transactionlist[i].Gateway;
b.PaymentRefNumber = transactionlist[i].PaymentRefNumber;
b.ReturnUrl = transactionlist[i].ReturnUrl;
b.State = transactionlist[i].State;
b.Uuid = transactionlist[i].Uuid;
bdto.Add(b);
}
Well obvously, bdto
length is less than transactionlist
length. 好吧, bdto
长度小于transactionlist
长度。
before your for loop you can resize bdto
to match transactionlist
在for循环之前,您可以调整bdto
大小以匹配transactionlist
I totally agree with @Ashkan and @Mureinik's answer, but just to improve code you can use AutoMapper . 我完全同意@Ashkan和@Mureinik的回答,但只是为了改进代码,你可以使用AutoMapper 。 It will reduce loop and iteration for every element. 它将减少每个元素的循环和迭代。 It seems that all the properties between these two objects is the same. 似乎这两个对象之间的所有属性都是相同的。
Mapper.CreateMap<Transaction,BankDepositHistoryDTO>();
BankDepositHistoryDTO obj = Mapper.Map<Transaction,BankDepositHistoryDTO>(TransactionObj);
Also if GetListoftransactions.GetAccountingListoftransactions();
另外如果GetListoftransactions.GetAccountingListoftransactions();
returns List<BankDepositHistoryDTO>
, you can directly return that object in method. 返回List<BankDepositHistoryDTO>
,可以直接在方法中返回该对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.