简体   繁体   中英

Umbraco 7 LINQ to filter Model children on date range

I have a collection of articles in Umbraco 7 which span multiple years and wanted to write a simple LINQ query to get items for the current year:

var press =  Model.Content.Children.Where(w => Convert.ToDateTime(w.GetPropertyValue("publicationDate")) >= new Date(1,1,2018));

This results in the error:

Delegate 'System.Func' does not take 1 arguments.

I'm contemplating just bunging the data in a list of T - unless someone can steer me in the right direction with filtering on Umbraco content nodes?

Thanks in advance.

I'm thinking something like this looks more "correct" to me, but it's untested. One thing to note is the way I make sure to get the property as DateTime directly from Umbraco. And also I figured comparing it to a DateTime instead of a Date might make a difference.

var press =  Model.Content.Children.Where(w => w.GetPropertyValue<DateTime>("publicationDate") >= new DateTime(2018,1,1));

Your problem is that you're using Date instead of DateTime . Date is not a standard .NET type - it is most likely from some other DLL you have referenced in your project.

This means it is not comparable with DateTime which is the type of the data you are converting to when fetching data from Umbraco (and also the type we're using to store dates internally in Umbraco).

As mentioned in the other answer you should also be using the .GetPropertyValue<DateTime>() method to simply have Umbraco do the conversion for you. It would simplify your code a bit.

Apart from that - your query works fine if you just change it to use DateTime instead of Date - I've just verified that myself.

Consider putting the date in a variable first to avoid instantiating new instances of DateTime inside the Where :

var currentYear = new DateTime(2018, 1, 1);
var press =  Model.Content.Children.Where(x => x.GetPropertyValue<DateTime>("publicationDate") > currentYear);

// or your way:
var press =  Model.Content.Children.Where(w => Convert.ToDateTime(w.GetPropertyValue("publicationDate")) >= date);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM