我有一个userList
,需要从字符串中排除下面的代码
string[] userList={"gerald","admin","john"} ;
List<EventItem> logall= new List<EventItem>();
List<EventItem> logfilteruser= new List<EventItem>();
logall= Records.AsQueryable().Select(e => new EventItem(e)).ToList();
logall将拥有的所有记录
如何排除userList
下面是我排除userList的代码。
if (users != "") {
foreach (var filter in userList) {
logfilteruser= logall.Where(x => !x.depict.Contains(filter)).ToList();
}
描述是记录中的一个字符串属性,这有许多记录,下面是描述字符串值之一
depict= "username:ttgeraldrnttt0x18ECC03rnt";
depict= "username:ttjasonrnttt0x18ECC03rnt";
如果userList
只是一个value(gerald)
,则该代码有效。当userList
有多个时,它不起作用。结果显示所有记录都出来了,这是不正确的。
如何使用linq
或其他方式修复代码?谢谢,也很抱歉我英语不好。
这里我包括我的EventItem和记录以供参考
public class EventItem {
public int Id { get; set; }
public string LogName { get; set; }
public string depict{ get; set; }
public WinEventItem(EventRecord record) {
Id = record.Id;
LogName = record.LogName;
depict= record.FormatDescription();
}
}
public List<EventRecord> Records { get; private set; }
private Records = new List<EventRecord>();
如果depict
属性是单个字符串,这将起作用:
logfilteruser = logall.Where(x => !userList.Any(u => x.depict.Contains(u))).ToList();
理论上,这也应该比foreach (var filter in userList)
执行得稍好,因为一旦Any()
在userlist
中找到匹配项,它就会返回,不需要每次都枚举整个集合(即使已经找到匹配项)。
编辑
下面是一个示例控制台应用程序,展示了它的工作原理。
我创建了一个示例类,而不是从EventRecord
继承的完整类。它为FormatDescription
返回一个字符串,就像EventRecord
一样。
class Program
{
static void Main(string[] args)
{
// Create some test data
List<TestEventRecord> Records = new List<TestEventRecord>();
Records.Add(new TestEventRecord { Value = "username:ttgeraldrnttt0x18ECC03rnt" });
Records.Add(new TestEventRecord { Value = "username:ttjasonrnttt0x18ECC03rnt" });
string[] userList = { "gerald", "admin", "john" };
List<EventItem> logall = new List<EventItem>();
List<EventItem> logfilteruser = new List<EventItem>();
// Contains all entries
logall = Records.AsQueryable().Select(e => new EventItem(e)).ToList();
// Contains only 1 entry as the list is filtered
logfilteruser = logall.Where(x => !userList.Any(u => x.depict.Contains(u))).ToList();
}
}
public class EventItem
{
public int Id { get; set; }
public string LogName { get; set; }
public string depict { get; set; }
public EventItem(TestEventRecord record)
{
Id = record.Id;
LogName = record.LogName;
depict = record.FormatDescription();
}
}
// Example class for testing
public class TestEventRecord
{
public int Id { get; set; }
public string LogName { get; set; }
public string Value { get; set; }
public string FormatDescription()
{
return Value;
}
}
每次循环时都要重新过滤原始列表。尝试以下操作:
logfilteruser = logall;
foreach (var filter in userList)
{
logfilteruser = logfilteruser.Where(x => !x.depict.Contains(filter)).ToList();
}