DoI*_*oIt 4 c# arraylist visual-studio-2012
我有一个C#方法,我username在列表中查找某些文本,其中包含格式username + datetime中的元素,如果文本的任何部分与列表中的元素匹配,则必须从列表中删除整个元素
添加到的方法 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);
}
Run Code Online (Sandbox Code Playgroud)
现在我想要一个删除元素的方法,如果它匹配用户名或元素的任何部分
if (activeUsers.Contains(active_user))
{
activeUsers.Remove(active_user);
}
Run Code Online (Sandbox Code Playgroud)
你可以做点什么
activeUsers.RemoveAll(u => u.Contains(active_user));
Run Code Online (Sandbox Code Playgroud)
这将匹配并删除activeUser包含文本的所有元素active_user.
当其他答案正确时,您应注意它们将删除所有匹配项。例如,active_user = "John"将删除“ John”,“ John123”,“ OtherJohn”等。
您可以使用正则表达式进行测试,或者如果用户名没有括号,请按以下方式进行测试:
string comp = active_user + "("; // The ( is the start of the date part
activeUsers.RemoveAll(u => u.StartsWith(comp));
Run Code Online (Sandbox Code Playgroud)
另请注意,这是区分大小写的。