Reputation: 67
I am building a web service in C# using Umbraco's uQuery that takes 2 parameters and returns a JSON serialized string containing a list of search results.
I pass in a string array containing the tags for my search e.g. ["red", "blue"]
public string GetResultsHttp(string[] tags)
{
IEnumerable<Node> nodes;
// first get all nodes that are of the right content type
nodes = uQuery.GetNodesByType("MyPage");
// if tags are passed in then limit the results to those tags
if (tags.Length > 0)
{
nodes = nodes.Where(n => tags.Contains(n.Parent.GetProperty("tags").Value));
}
// return the node list as a serialized string
}
So far so good and that works to return results that contain any of my tags.
now I want to limit the results by date. The dates array looks like this ["201410", "201411"] so it's year followed by month.
I want to further limit my result set to those results that have a myDate property where the month and year matches any of the months and years in my date array.
So my code becomes this:
public string GetResultsHttp(string[] tags, string[] dates)
{
IEnumerable<Node> nodes;
// first get all nodes that are of the right content type
nodes = uQuery.GetNodesByType("MyPage");
// if tags are passed in then limit the results to those tags
if (tags.Length > 0)
{
nodes = nodes.Where(n => tags.Contains(n.Parent.GetProperty("tags").Value));
}
if (dates.Length > 0)
{
// the format of the incoming date
string formatString = "yyyyMM";
foreach (string dateTag in dates)
{
DateTime dt = DateTime.ParseExact(dateTag, formatString, null);
nodes = nodes.Where(n => (dt.Month.Equals(n.GetProperty<DateTime>("myDate").Month)) && (dt.Year.Equals(n.GetProperty<DateTime>("myDate").Year)));
}
}
// return the node list as a serialized string
}
The above obviously works fine for 1 date, but if I pass in 2 it stands to reason that one page can't have 2 dates.
Also, I'm sure there is a much simpler way of achieving this :)
Thanks Travis
Upvotes: 2
Views: 1861
Reputation: 203821
Currently your query is ensuring that the date is equal to All of the dates in dates
. You want it to filter where Any
of the dates are in dates
.
var nodes= uQuery.GetNodesByType("MyPage")
.Where(n => tags.Contains(n.Parent.GetProperty("tags").Value)
.Where(n => dates.Any(dateString =>
DatesAreEqual(dateString, n.GetProperty<DateTime>("myDate"));
(DatesAreEqual
can contain all of the logic for comparing the dates, rather than trying to inline all of the parsing/comparing.)
Upvotes: 1