Home > Blockchain >  Why not all the items in the List that not contains the string not removed from the List?
Why not all the items in the List that not contains the string not removed from the List?

Time:10-19

var g = urls;
if (g.Count > 1)
{
     for(int i = g.Count - 1; i > 0; i--)
     {
          if (!g[i].Contains("Test"))
          {
                g.RemoveAt(i);
          }
     }
 }

I create a copy of the List then checking for specific string in each item but there are 23 items left in g one of them is not containing the word "Test" but was not removed it's the first item in the list at index 0.

CodePudding user response:

Because your for loop is not touching element present at index 0, to fix this issue update your for loop to

  for(int i = g.Count - 1; i >= 0; i--)
  {                        //^^^^ This is missing in your code
        if (!g[i].Contains("Test"))
        {
               g.RemoveAt(i);
         }
  }

To make it more readable, you can traverse from start instead of reverse traversal and store expected element of g into a new list.

  var result = new List<string>();
  for(int i = 0; i < g.Count; i  )
  {
        if (g[i].Contains("Test"))
        {
               result.Add(g[i]);
         }
  }

To make it more elegant you can use Linq Where() clause,

var result = g.Where(x => x.Contains("Test")).ToList();

If you are looking for a solution which actually update input list (in Your case it is g), then you can use solution suggested by @canton7,

g.RemoveAll(item => !item.Contains("Test"))
Console.WriteLine(string.Join(" ", g));

.RemoveAll()


.NET Fiddle

CodePudding user response:

var g = urls.Where(u => u.Contains("Test")).ToList();
  •  Tags:  
  • c#
  • Related