Damkulul
Damkulul

Reputation: 1476

How to remove an item in a list that equals a specific string

I have a list that contains this data: "start it", "start it now", "don't start it".

I need to find and remove items that are equal to "start it". Is there a simple way to do that?

Upvotes: 1

Views: 6852

Answers (6)

Mohit S
Mohit S

Reputation: 14044

This might do the trick for you

List<string> items = new List<string>() { "start it now", "start it", "don't start it" };
items.RemoveAll(x => x.Equals("start it"));
//or
items.RemoveAll(x => x == "start it");

Both, Contains and Equals are using string comparison. Since your comparison is of type string, Contains will check if the passed parameter is part of the string, whereas Equals compares the complete string for equality.

Upvotes: 0

zahra
zahra

Reputation: 1

try this:

 string   mystring = "start it,start it now,don't start it";
 ArrayList strings = new ArrayList(mystring.Split(new char[] { ',' }));

 for (int i = 0; i <strings.Count; i++)
 {
     if (strings[i].ToString()=="start it")
     {
         strings.RemoveAt(i);
     }
 }

and dont forget: using System.Collections;

Upvotes: 0

Praburaj
Praburaj

Reputation: 613

Try this:

It removes all the string thatis equal to "start it".

list.RemoveAll(x => x.Equals("start it"));

It removes all the string that contains the sentence"start it".

list.RemoveAll(x => x.Contains("start it"));

Upvotes: 0

fubo
fubo

Reputation: 45947

If you want to delete all items that contain that substring "start it" you have to do

List<string> items = new List<string>() { "start it", "start it now", "don't start it" };
items.RemoveAll(x => x.Contains("start it"));

if you want to remove all items that equal "start it" you have to

items.RemoveAll(x => x == "start it");

Upvotes: 6

Anup Sharma
Anup Sharma

Reputation: 2083

try list.RemoveAll(x=>x=="start it"); where list is your List<string>

Upvotes: 3

Saadi
Saadi

Reputation: 2237

Here is what you can do:

List<string> list = new List<string>() { "start it", "start it now", "don't start it" };
list.RemoveAll(x => x.Contains("start it"));

Upvotes: -2

Related Questions