Pregunta

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);
}
¿Fue útil?

Solución

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.

Otros consejos

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.

var user = activeUsers.FirstOrDefault(au => au.Contains(active_user);

if(user != null)
    activeUsers.Remove(user);

if you are only wanting to remove the first match, else :

var users = activeUsers.Where(au => au.Contains(active_user);

foreach(var user in users)
    activeUsers.Remove(user);

Or more simply, the RemoveAll method Eric answered with.

If i Want to remove Numeric String Values List Items from my List

 List<ModelName> ModelList = new List<ModelName>();

 var regex = new Regex(@"\d");

 foreach(var item in ModelList.ToList())
                {
                    if (regex.IsMatch(item.PropertyName))
                    {
                        ModelList.RemoveAll(t => t.PropertyName== item.PropertyName);//Or
                        ModelList.RemoveAll(t => t.PropertyName.Contains(item.PropertyName));//Or You Can Use Contains Method
                    }
                }

 return ModelList;

This will remove all items from list those having Numeric values as a string and return only Character String in List items

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top