Home > database >  How to remove a string from the list, by looking at a certain letter?
How to remove a string from the list, by looking at a certain letter?

Time:11-26

var countries = new List<string>() { "India", "Australia", "Austria", "Canada", "Mexico", "Japan" };
            foreach(string country in countries)
            {
                if (country.StartsWith("A"))
                {
                    countries.Remove(country);
                }
            }
            foreach (string country in countries)
            {
                Console.WriteLine(country);
            }

For instance I would like to get rid of countries starting with the letter A

CodePudding user response:

I would suggest you to use RemoveAll() (link to documentation) which requires a condition to know if the element has to be removed or not

You could do :

// The List declaration you provided
var countries = new List<string>() { "India", "Australia", "Austria", "Canada", "Mexico", "Japan" };

// Replace your first `foreach(string country in countries)` with this line
countries.RemoveAll(country => country.StartsWith("A"));

// The way of displaying data you provided
foreach (string country in countries)
{
    Console.WriteLine(country);
}

Edit : As fubo said in the comments, "if you want to perform a case-insensitive search, you should provide a StringComparison rather than using ToUpper()", as I did in the uneditted answer.

The code would be :

// The List declaration you provided
var countries = new List<string>() { "India", "Australia", "Austria", "Canada", "Mexico", "Japan" };

// Replace your first `foreach(string country in countries)` with this line
countries.RemoveAll(country => country.StartsWith("a", StringComparison.InvariantCultureIgnoreCase));

// The way of displaying data you provided
foreach (string country in countries)
{
    Console.WriteLine(country);
}

CodePudding user response:

Approach with RemoveAll()

List<string> countries = new List<string>() { "India", "Australia", "Austria", "Canada", "Mexico", "Japan" };
countries.RemoveAll(country => country.StartsWith("A"));
countries.ForEach(Console.WriteLine);

CodePudding user response:

Yes you can use the RemoveAll() property to get the result you want.

var countries = new List<string>() { "India", "Australia", "Austria"};

countries.RemoveAll(Country=>country.StartsWith("A"))
  • Related