从包含字符串的ArrayList中删除所有元素 [英] Remove all elements from an ArrayList that contains string
问题描述
我一直在尝试找出如何删除ArrayList中值包含一些文本字符串的元素.
I've been trying to figure out how to remove elements in my ArrayList where the value contains some text string.
我的阵列看起来像这样:
My Array could look like this:
[0] "\"MAERSKA.CO\",N/A,N/A,N/A,N/A,N/A,N/A"
[1] "\"GEN.COABB.ST\",N/A,N/A,N/A,N/A,N/A,N/A"
[2] "\"ARCM.ST\",\"Arcam AB\",330.00,330.50,332.00,330.50,330.00"
我的ArrayList是这样创建的:
And my ArrayList is created like this:
string stringToRemove = "NA";
ArrayList rows = new ArrayList(csvData.Replace("\r", "").Split('\n'));
所以问题是我如何删除所有包含"NA"的条目.我已经尝试过用Contains的几种组合来使用RemoveAt或RemoveAll,但是我似乎无法正确获取代码.
So the question is how I delete all entries that contains "NA". I have tried the RemoveAt or RemoveAll with several combinations of Contains but i cant seem to get the code right.
如果可以避免,我不想制作一个新的阵列.
I do not want to make a new Array if it can be avoided.
问候弗莱明(Flemming)
Regards Flemming
推荐答案
如果要在实例化变量之前减少ArrayList,请考虑使用LINQ:
If you want to reduce your ArrayList before instantiate your variable, consider using LINQ:
ArrayList rows = new ArrayList(csvData.Replace("\r", "").Split('\n').Where(r => !r.Contains(stringToRemove)).ToList());
如果要在实例化后减少ArrayList,可以尝试以下操作:
If you want to reduce your ArrayList after instantiation, you can try this:
for (int i = 0; i < rows.Count; i++)
{
var row = (string)rows[i];
if (row.Contains(stringToRemove))
{
rows.RemoveAt(i);
i--;
}
}
这篇关于从包含字符串的ArrayList中删除所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!