Reputation: 2156
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
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
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
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
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