i want to fetch the records between 7am and 3pm . How to write linq query for the same?
code
var items = Pirs.Where(a => !a.dataFrame.EndsWith("AAAAAAAAAAA=") && (fromDate == null || fromDate.Value.Date <= TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(a.timestamp), TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")).Date) && (toDate == null || toDate.Value.Date >= TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(a.timestamp), TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")).Date) && (a.timestamp.Hour > 7 || a.timestamp.Hour < 15))
.GroupBy(a => a.dataFrame.Substring(a.dataFrame.Length - 12))
.Select(g => g.First()).OrderBy(a => a.timestamp);
sample data
timestamp "2017-07-21T14:06:02.203Z"
The way your question is written, it is difficult to understand exactly what you're asking, so I will give you a general way of achieving what (I think) you want.
Say you have a class, Foo
:
class Foo
{
public DateTime date { get; set; }
}
Given a List<Foo>
, you can get all instances of Foo
in that list who's date
property is between certain hours like so:
var myList = new List<Foo>();
int startHour = 7; // 7am
int endHour = 15; // 3pm
var result = myList.Where(item => item.date.Hour >= startHour && item.date.Hour <= endHour);
The result
enumerations contains all items in myList
whos date
property's Hour
field is between startHour
and endHour
inclusive.
Something to note, you could use an extension method to greatly simplify this:
public static bool Between(DateTime input, int x, int y)
{
return (input.Hour => x && input.Hour <= y);
}
var result = myList.Where(item => item.date.Between(7, 15));
However, you mentioned you were using Entity Framework, which this second solution is incompatible with, since when you query a DbSet
, that operation isn't performed by your program, but translated into SQL by EF and executed by the DB provider instead. Using an extension method in your query would require loading up everything into memory first, which I do not recommend.