public static IQueryable<T> FilterExact<T>(this IQueryable<T> details, int c, Func<T, int> lambda)
{
if (c > 0)
{
details = details.Where(s => lambda(s).Equals(c));
}
return details;
}
The above is what I have so far. The current error exist due to linq to entity error, which can be fixed by switching it to IEnumerable, but instead, what I want is to be able to make a new linq Expression, instead of executing the function directly.
How would I go about doing this? I would prefer mapping from Func<T, int>
to Expression<Func<T, bool>>
.
The reason I need this is because there are a few places where code just as below exist, except the same code is copy-pasted multiple times with a different entity column associated. I want to create this as a method to prevent code duplication, but need a way to specify which column to use. (I first tried reflection, but it slowed everything down significantly.)
if (!string.IsNullOrEmpty(searchCriteria.StudyDate))
{
if (searchCriteria.StudyDate.Contains(":"))
{
string[] dates = searchCriteria.StudyDate.Split(':');
DateTime startDate;
DateTime endDate;
DateTime.TryParse(dates[0], out startDate);
DateTime.TryParse(dates[1], out endDate);
if (startDate.Year > 1 && endDate.Year > 1 && endDate > startDate)
{
dropChargesStudies = dropChargesStudies.Where(s => s.PERFORMED >= startDate && s.PERFORMED <= endDate);
}
else
{
throw new Exception("The study date is invalid.");
}
}
else
{
DateTime studyDateParsed;
DateTime.TryParse(searchCriteria.StudyDate, out studyDateParsed);
if (studyDateParsed.Year > 1)
{
dropChargesStudies = dropChargesStudies.Where(s => s.PERFORMED.Value == studyDateParsed);
}
else
{
throw new Exception("The study date is invalid.");
}
}
}