我试图根据某些条件过滤对象列表。我已经看到一些帖子在他们的LINQ查询中使用三元运算符来完成此任务。
在此代码段的底部是我的LINQ查询。我希望它能够测试每个where
,而只是尝试第一个where
并留下其余部分。 List
不包含我期望的数据。我做错了什么?
private ObservableCollection<LogEvent> m_LogEvents = ApplicationData.MainLogEntries.LogEvents;
public ObservableCollection<LogEvent> LogEvents
{
get { return m_LogEvents; }
set { m_LogEvents = value; RaisePropertyChanged("LogEvents"); }
}
private bool m_ViewDebugLogs = false;
public bool ViewDebugLogs
{
get { return m_ViewDebugLogs; }
set { m_ViewDebugLogs = value; RaisePropertyChanged("ViewDebugLogs"); FilterList(); }
}
private bool m_ViewErrorLogs = true;
public bool ViewErrorLogs
{
get { return m_ViewErrorLogs; }
set { m_ViewErrorLogs = value; RaisePropertyChanged("ViewErrorLogs"); FilterList(); }
}
private bool m_ViewInfoLogs = true;
public bool ViewInfoLogs
{
get { return m_ViewInfoLogs; }
set { m_ViewInfoLogs = value; RaisePropertyChanged("ViewInfoLogs"); FilterList(); }
}
private void FilterList()
{
List<LogEvent> selectedEvents = (from x in LogEvents
where (ViewDebugLogs) ? x.Level == "Debug" : false
where (ViewErrorLogs) ? x.Level == "Error" : false
where (ViewInfoLogs) ? x.Level == "Info" : false
select x).ToList();
}
编辑:这样做的目的是,如果启用了适当的bool ViewDebugLogs
,ViewErrorLogs
或ViewInfoLogs
或这三者的任意组合,则会按适当的类型过滤日志。
我从答案中尝试了以下内容但没有成功:
仅获得Debug Logs
:
List<LogEvent> selectedEvents = (from x in LogEvents
where (ViewDebugLogs == true) ? x.Level == "Debug" : false
|| (ViewErrorLogs == true) ? x.Level == "Error" : false
|| (ViewInfoLogs == true) ? x.Level == "Info" : false
select x).ToList();
仅获得Debug Logs
:
List<LogEvent> selectedEvents = (from x in LogEvents
where (ViewDebugLogs == true) ? x.Level == "Debug" : true
|| (ViewErrorLogs == true) ? x.Level == "Error" : true
|| (ViewInfoLogs == true) ? x.Level == "Info" : true
select x).ToList();
这没有任何结果:
List<LogEvent> selectedEvents = (from x in LogEvents
where (ViewDebugLogs == true) ? x.Level == "Debug" : true
where (ViewErrorLogs == true) ? x.Level == "Error" : true
where (ViewInfoLogs == true) ? x.Level == "Info" : true
select x).ToList();
答案 0 :(得分:6)
多个where
条件被连接,就像您使用AND
一样。如果您尝试OR
,则应使用||
代替。
List<LogEvent> selectedEvents = (from x in LogEvents
where (ViewDebugLogs) ? x.Level == "Debug" : false
|| (ViewErrorLogs) ? x.Level == "Error" : false
|| (ViewInfoLogs) ? x.Level == "Info" : false
select x).ToList();
答案 1 :(得分:4)
您可以使用
List<LogEvent> selectedEvents = (from x in LogEvents
where (ViewDebugLogs && x.Level == "Debug")
|| (ViewErrorLogs && x.Level == "Error")
|| (ViewInfoLogs && x.Level == "Info")
select x).ToList();
这更清楚(在我看来)。请注意表达式部分周围的( )
:我想确定评估AND和OR的顺序。
答案 2 :(得分:1)
Where
子句可以是where (ViewDebugLogs) ? x.Level == "Debug" : ((ViewErrorLogs) ? x.Level == "Error" : ((ViewInfoLogs) ? x.Level == "Info" : false))