Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing an element from list if it contains particular text in it

I have a C# method in which I look for certain text say username in a list with element in the format username + datetime and if any part of text matches the element in the list, then the entire element has to be removed from the list

Method to add to the c# List

string active_user = model.UserName.ToString();
string datetime = "(" + DateTime.Now + ")";
List<string> activeUsers = new List<string>();

if (activeUsers.Any(str => str.Contains(active_user)))
{
    //do nothing
}
else
{
    activeUsers.Add(active_user+datetime);
}

Now I would like a method that deletes the element if it matches the username or any part of element something like

if (activeUsers.Contains(active_user))
{
    activeUsers.Remove(active_user);
}
like image 848
DoIt Avatar asked May 09 '14 17:05

DoIt


2 Answers

While the other answers are correct, you should note that they will delete any matches. For example, active_user = "John" will remove "John", "John123", "OtherJohn", etc.

You can use regular expressions to test, or if user names don't have parentheses, do your test like this:

string comp = active_user + "(";     // The ( is the start of the date part
activeUsers.RemoveAll(u => u.StartsWith(comp));

Also note, this is case sensitive.

like image 64
Johnny Mopp Avatar answered Oct 22 '22 10:10

Johnny Mopp


You can do something like

activeUsers.RemoveAll(u => u.Contains(active_user));

That will match and remove all elements of activeUser that contain the text in active_user.

like image 43
Eric J. Avatar answered Oct 22 '22 09:10

Eric J.