[英]Removing an element in string list in c#, gives error(ArgumentOutOfRangeException)
I'm trying to filter my string list by getting input, but get this error: ArgumentOutOfRangeException: Index was out of range.我试图通过获取输入来过滤我的字符串列表,但出现此错误:ArgumentOutOfRangeException:索引超出范围。 Must be non-negative and less than the size of the collection.
必须为非负数且小于集合的大小。 Parameter name: index
参数名称:索引
private List<string> title = new List<string>();
private int cellNumber { get; set; }
private int counter = 0;
inputField.onValueChanged.AddListener(delegate { Search(cellNumber-counter); });
public void Search(int size)
{
for (int i = 0; i < size; i++)
{
if (!title[i].ToLower().Contains(inputField.text.ToLower()) && inputField.text != "")
{
title.RemoveAt(i);
counter++;
}
}
}
If you have hits your list size decreases for each removed item.如果您点击了每个删除的项目,您的列表大小就会减少。
So even assuming you are passing in the correct size
of the list, the iterator variable i
at some point at the end runs longer than the new smaller size of your list after removing items => ArgumentOutOfRangeException!因此,即使假设您传递的列表
size
正确,迭代器变量i
在最后某个时刻运行的时间也比删除项目后列表的新较小大小长 => ArgumentOutOfRangeException!
What you could do is keep updating the size and skip i++
whenever you remove an item like eg您可以做的是不断更新大小并在删除诸如 eg 之类的项目时跳过
i++
public void Search()
{
if (string.IsNullOrWhiteSpace(inputField.text))
{
return;
}
var size = title.Count;
var i = 0;
while(i < size)
{
if (!title[i].ToLower().Contains(inputField.text.ToLower()))
{
title.RemoveAt(i);
size--;
}
else
{
i++;
}
}
}
Note that there is a simple method that already covers this without further effort: List<t>.RemoveAll
请注意,有一个简单的方法已经涵盖了这一点,无需进一步努力:
List<t>.RemoveAll
public void Search()
{
if(string.IsNullOrWhiteSpace(inputField.text))
{
return;
}
// remove all matches
title.RemoveAll(t => !t.ToLower().Contains(inputField.text.ToLower()));
}
Though you might be even more interested in using Linq Where
in order to return a new collection with the hits without modifying the original one尽管您可能对使用Linq
Where
更感兴趣,以便在不修改原始集合的情况下返回包含匹配项的新集合
using System.Linq;
...
public string[] Search()
{
if(string.IsNullOrWhiteSpace(inputField.text))
{
return new string[0];
}
// remove all matches
return title.Where(t => t.ToLower().Contains(inputField.text.ToLower())).ToArray();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.