Venkat
Venkat

Reputation: 2156

Remove elements in an array containing a certain word/string in a single line of statement

I have an array:

 List<String> TagArray = new List<string>(TagString.Split(','));

I want to remove certain elements, in the array; say - if the values contain the letter 'AAA'.

Is there a single line of statement in C# by which we can achieve the desired result?

Upvotes: 1

Views: 5062

Answers (4)

Evan Frisch
Evan Frisch

Reputation: 1374

Try this:

TagArray.RemoveAll(item => item.Contains("AAA"));

RemoveAll will remove all the items that would return true from the predicate you define. You can do this multiple time or you can || a bunch of contains together within one RemoveAll.

Upvotes: 5

Luk&#225;š Neoproud
Luk&#225;š Neoproud

Reputation: 902

There is a method available in List<T> : RemoveAll(Predicate<T>)

var list = new List<string> {"AAABBBCCC", "AABBCC", "ABC", "CCAAACC"};
list.RemoveAll(s => s.Contains("AAA")); // Removes the first and the last element

RemoveAll() "iterates" over the list and provides you each element. The s represents an element from the list and the code after => is a condition. When the condition is true, the element is removed. The condition doesn't have to use the s variable, it can be arbitrary block that returns bool value.

So you can also write this:

list.RemoveAll(s =>
{
    return a == 5;
});

Upvotes: 0

user222427
user222427

Reputation:

 static void Main(string[] args)
    {

        string TagString = "WAAAA,APPLE";

        List<String> TagArray = new List<string>(TagString.ToUpper().Split(',')).Where(x => !x.Contains("AAA")).ToList();

    }

1 line and it works

 List<String> TagArray = new List<string>(TagString.ToUpper().Split(',')).Where(x => !x.Contains("AAA")).ToList();

Upvotes: 0

Kundan Singh Chouhan
Kundan Singh Chouhan

Reputation: 14282

You could use LINQ here. For example

List<String> TagArray = TagString.Split(',')
    .Where(tag => tab.IndexOf("AAA") < 0)
    .ToList();

Remember to add System.Linq namespace.

Hope this helps !!

Upvotes: 0

Related Questions