TimeSpan in lambda expressions

I want to get a lambda function that will query for items that were sent at the last minute. How to determine this?

var items= Items.Where(i=>DateTime.Now.Subtract(i.Date)...)
+3
source share
4 answers

If the elements have a Date property, you can do:

DateTime startDate = DateTime.Now - new TimeSpan(0,1,0);
var items = Items.Where( i => i.Date >= startDate );

You can put the math in the Where statement directly, but it will be recalculated for each element, so I prefer to leave the original time outside the instruction.

+6
source

Make your choice

var items= Items.Where(i => DateTime.Now.Subtract(i.Date).TotalMinutes < 1)

or

var items= Items.Where(i => DateTime.Now.Subtract(i.Date).TotalSeconds <= 60)
+8
source

:

DateTime cutoffPoint = DateTime.Now.AddMinutes(-1);
var items = Items.Where(i => (i.Date >= cutoffPoint));
+5
var items = Items.Where(i => DateTime.Now.Subtract(i.Date).TotalSeconds <= 60);

, , DateTime.Now , .

+2

Source: https://habr.com/ru/post/1721829/


All Articles