Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String list remove

I have this code:

List<string> lineList = new List<string>();

foreach (var line in theFinalList)
{
    if (line.PartDescription != "")
        lineList.Add(line.PartDescription + " " + line.PartNumber + "\n");
    else
        lineList.Add("N/A " + line.PartNumber + "\n");

    //
    //This is what I am trying to fix:
    if (lineList.Contains("FID") || lineList.Contains("EXCLUDE"))
        // REMOVE THE item in the lineList
}

I am trying to go through theFinalList in a foreach loop and add each line to a new list called lineList. Once added, I want to remove any entries from that list that contain the text "FID" or "EXCLUDE".

I am having trouble removing the entry, can someone help me?

like image 622
theNoobGuy Avatar asked Dec 10 '22 06:12

theNoobGuy


2 Answers

why add them when you want to remove them right after:

lineList = theFinalList.Select( line => 
{
    if (line.PartDescription != "")
        return line.PartDescription + " " + line.PartNumber + "\n";
    else
        return "N/A " + line.PartNumber + "\n";
})
.Where(x => !(x.Contains("FID") || x.Contains("EXCLUDE")))
.ToList();
like image 171
BrokenGlass Avatar answered Dec 11 '22 18:12

BrokenGlass


The following code sample iterates through the lineList and removes lines that contain FID or EXCLUDE.

for(int i = lineList.Count - 1; i >= 0; i--)
{
    if (lineList[i].Contains("FID") || lineList[i].Contains("EXCLUDE"))
       lineList.RemoveAt(i);
}

It is important to traverse a list in reverse order when deleting items.

like image 24
Casperah Avatar answered Dec 11 '22 19:12

Casperah