错误索引超出范围。必须是非负数且小于集合的大小
Posted
技术标签:
【中文标题】错误索引超出范围。必须是非负数且小于集合的大小【英文标题】:Error Index was out of range. Must be non-negative and less than the size of the collection 【发布时间】:2019-08-28 13:46:12 【问题描述】:我正在尝试用 for 填充我的 DTO 对象,但出现此错误:
Index was out of range. Must be non-negative and less than the size of the collection
这是我的代码:
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;
我在这里收到了这条消息
bdto[i].AccountId = transactionlist[i].AccountId;
【问题讨论】:
【参考方案1】:您创建了一个空列表,并且没有向其中添加元素。你必须先添加一个元素,然后更新它的属性:
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);
【讨论】:
【参考方案2】:很明显,bdto
长度小于 transactionlist
长度。
在您的 for 循环之前,您可以调整 bdto
的大小以匹配 transactionlist
【讨论】:
【参考方案3】:我完全同意@Ashkan 和@Mureinik 的回答,但只是为了改进代码,您可以使用AutoMapper。它将减少每个元素的循环和迭代。这两个对象之间的所有属性似乎都是相同的。
Mapper.CreateMap<Transaction,BankDepositHistoryDTO>();
BankDepositHistoryDTO obj = Mapper.Map<Transaction,BankDepositHistoryDTO>(TransactionObj);
另外如果GetListoftransactions.GetAccountingListoftransactions();
返回List<BankDepositHistoryDTO>
,你可以直接在方法中返回那个对象。
【讨论】:
以上是关于错误索引超出范围。必须是非负数且小于集合的大小的主要内容,如果未能解决你的问题,请参考以下文章