gpt4 book ai didi

c# - 索引超出范围。必须是非负误差

转载 作者:行者123 更新时间:2023-11-30 18:58:47 27 4
gpt4 key购买 nike

我不断收到索引超出范围的异常。不得为非负数且小于集合的大小。

问题是当我检查 toRemove 时,计数低于响应者。那么这个错误是怎么发生的呢?如果 respondents 中有 5 个,而 toRemove 只有 3 个,那么这个错误是如何发生的?

var respondents = RespondentRepository.GetRespondents(UserSession, fieldsToInclude);

// iterate through the respondents. If search query not like results throw the result away.
List<int> toRemove = new List<int>();
for (int i = 0; i < respondents.Count; i++)
{
if (!respondents[i].EmailAddresses.Any())
toRemove.Add(i);
else
{
bool checkSingleEmail = false;
bool checkAllEmails = false;
for (int j = 0; j < respondents[i].EmailAddresses.Count; j++)
{
checkSingleEmail = respondents[i].EmailAddresses[j].Address.ToString().Contains(query);

if (checkSingleEmail == true)
checkAllEmails = true;

if (respondents[i].EmailAddresses.Count == 1 && j == 0 && checkAllEmails == false)
toRemove.Add(i);
else if (checkAllEmails == false && j+1 == respondents[i].EmailAddresses.Count)
toRemove.Add(i);
}
}
}

foreach (var respRemove in toRemove)
{
respondents.RemoveAt(respRemove);
}

最佳答案

如果你想使用索引,你可以这样写:

foreach (var respRemove in toRemove.OrderByDesc(r => r).ToList())
{
respondents.RemoveAt(respRemove);
}

关于c# - 索引超出范围。必须是非负误差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19567778/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com