从包含字符串的 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"的条目.我已经尝试使用包含的几种组合的 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.
问候弗莱明
推荐答案
如果您想在实例化变量之前减少 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屋!