我不断得到索引超出范围异常。不得为非负数且小于集合的大小。
问题是当我检查toRemove
计数低于受访者时。那么这个错误是怎么发生的呢?如果有 5 个respondents
并且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);
}