1

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"   

And my ArrayList is created like this:

string stringToRemove = "NA";   
ArrayList rows = new ArrayList(csvData.Replace("\r", "").Split('\n'));

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.

Regards Flemming

Flemming Lemche
  • 169
  • 1
  • 3
  • 23

2 Answers2

1

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());

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--;
    }
}
Simser
  • 302
  • 2
  • 10
0

The following code creates a list as output containing all strings except "N/A":

var outputs = new List<string>();
foreach (var item in input)
{
    var splitted = item.Split(',');
    foreach (var splt in splitted)
    {
        if (splt != "N/A")
        {
            outputs.Add(splt);
        }
    }
}

The input is your array.

Mahdi
  • 3,199
  • 2
  • 25
  • 35
  • I think the question was to remove entries/rows containing "N/A", not creating a new list of all words except "N/A". – Simser Dec 22 '16 at 13:24
  • Thanks for contribution. I can use this solution elsewere but answers below fits solution to question better. – Flemming Lemche Dec 23 '16 at 09:36