我试图通过查询字符串过滤结果,但不确定最佳方法,到目前为止我所拥有的是:
var topic = Request.QueryString["topic"];
var date = Request.QueryString["date"];
var keyword = Request.QueryString["keyword"];
if (!string.IsNullOrEmpty(topic) || !string.IsNullOrEmpty(date) || !string.IsNullOrEmpty(keyword))
{
items = root.Children().Where(x => x.IsDocumentType("Event-Item") &&
x.GetPropertyValue("eventTitle").ToString().Contains(topic) ||
x.GetPropertyValue("eventDates").ToString().Contains(date) ||
x.GetPropertyValue("eventSummary").ToString().Contains(keyword)).OrderByDescending(x => x.CreateDate).ToList();
}
else
{
items = root.Children().Where(x => x.IsDocumentType("Event-Item")).OrderByDescending(x => x.CreateDate).ToList();
}
这看起来是否正确?这样做有更好(更正确)的方法吗? 非常感谢任何帮助。
答案 0 :(得分:1)
我会把它分解如下。你总是过滤“Event-Item”,所以从if / else中取出然后先做。然后检查空值并根据需要进行过滤。最后,因为你总是在排序,所以在一切之后都这样做。
var topic = Request.QueryString["topic"];
var date = Request.QueryString["date"];
var keyword = Request.QueryString["keyword"];
items = root
.Children()
.Where(x => x.IsDocumentType("Event-Item"));
if (!string.IsNullOrEmpty(topic) || !string.IsNullOrEmpty(date) || !string.IsNullOrEmpty(keyword))
{
items = items.Where(x =>
x.GetPropertyValue("eventTitle").ToString().Contains(topic) ||
x.GetPropertyValue("eventDates").ToString().Contains(date) ||
x.GetPropertyValue("eventSummary").ToString().Contains(keyword));
}
items = items.OrderByDescending(x => x.CreateDate);
答案 1 :(得分:1)
每个学期的条件where
怎么样?
string topic = Request.QueryString["topic"];
string date = Request.QueryString["date"];
string keyword = Request.QueryString["keyword"];
var filteredItems = root.Children()
.Where(x => x.IsDocumentType("Event-Item"));
if (!string.IsNullOrEmpty(topic))
filteredItems = filteredItems.Where(x => x.GetPropertyValue("eventTitle")
.ToString()
.Contains(topic));
if (!string.IsNullOrEmpty(date))
filteredItems = filteredItems.Where(x => x.GetPropertyValue("eventDates")
.ToString()
.Contains(date));
if (!string.IsNullOrEmpty(keyword))
filteredItems = filteredItems.Where(x => x.GetPropertyValue("eventSummary")
.ToString()
.Contains(keyword));
items = filteredItems.OrderByDescending(x => x.CreateDate).ToList();