Reputation: 1172
I have looked at many posts but unable to find an answer to my question.
I have a lot of queries that are using the Where condition as below. In the code it looks quite ugly, so i thought of using a predicate (dont know whether it is possible or not).
.Where(i => i.Timestamp <= date.ToUniversalTime() && i.Timestamp >= yearStart.ToUniversalTime())
I want this to become or something like this
.WhereYearTotal(date)
so the condition can be evaluated within "WhereYearTotal" function.
Edited:
I have already tried the extension method but it does not seem to work inside a nested query such as:
var query = (from o in db.tableA
select new {
monthly = db.tableA.WhereYearTotal(date),
}).FirstOrDefault();
I get a Null reference exception.
Upvotes: 0
Views: 290
Reputation: 39501
Predicate
is method passed as argument to Where
. What you want is not a predicate, but extension method
namespace ExtensionMethods
{
public static class MyExtensions
{
public static IEnumerable<MyClass> WhereYearTotal(this IEnuerable<MyClass> source, DateTime date)
{
return source.Where(i => i.Timestamp <= date.ToUniversalTime() && i.Timestamp >= yearStart.ToUniversalTime())
}
}
}
Upvotes: 0
Reputation: 51451
Just write your own extension method for IQueryable:
public static IQueryable<TSource> WhereYearTotal<TSource>(
this IQueryable<TSource> source,
DateTime date ) {
return source.Where(i => i.Timestamp <= date.ToUniversalTime() && i.Timestamp >= yearStart.ToUniversalTime());
}
Upvotes: 0
Reputation: 8421
This is done using extension methods. You need to create a static class and a static method for it.
static class MyHelper
{
public static IEnumerable<T> WhereYearTotal(this IEnumerable<T> input, DateTime d)
{
return input.Where( ... )
}
}
// usage : (the namespace for MyHelper must be in your using list)
myCollection.WhereYearTotal( DateTime.Now );
Upvotes: 0