Reputation: 968
I want to write a dynamic linq query that checks for 'where' condition based on two time frames, startTime and errorTime. The present code is here,
IQueryable<LogFormat> errorLines = null;
if (!string.IsNullOrEmpty(errorStartTime) && !string.IsNullOrEmpty(errorTime))
{
var sTime = DateTime.Parse(errorStartTime);
var eTime = DateTime.Parse(errorTime);
errorLines = from errorLine in File
where
(errorLine.DateTime >= sTime && errorLine.DateTime <= eTime) &&
(
errorLine.Level == "ERR"
|| errorLine.Level == "WARN"
)
select errorLine;
}
else if (!string.IsNullOrEmpty(errorStartTime))
{
var sTime = DateTime.Parse(errorStartTime);
errorLines = from errorLine in File
where
errorLine.DateTime >= sTime
&&
(
errorLine.Level == "ERR"
|| errorLine.Level == "WARN"
)
select errorLine;
}
else if (!string.IsNullOrEmpty(errorTime))
{
var eTime = DateTime.Parse(errorTime);
errorLines = from errorLine in File
where
errorLine.DateTime <= eTime
&&
(
errorLine.Level == "ERR"
|| errorLine.Level == "WARN"
)
select errorLine;
}
else
{
errorLines = from errorLine in File
where
errorLine.Level == "ERR"
|| errorLine.Level == "WARN"
select errorLine;
}
Can I know how to have just one query so that I can send start time and errortime dynamically to get the results?
Upvotes: 0
Views: 759
Reputation: 75316
You can make it dynamic by calling the where
clause multiple times, based on conditions:
var errorLines = File.Where(e => e.Level == "ERR"
|| e.Level == "WARN");
if (!string.IsNullOrEmpty(errorStartTime))
{
var sTime = DateTime.Parse(errorStartTime);
errorLines = errorLines.Where(e => e.DateTime >= sTime);
}
if (!string.IsNullOrEmpty(errorTime))
{
var eTime = DateTime.Parse(errorTime);
errorLines = errorLines.Where(e => e.DateTime <= eTime);
}
Upvotes: 2
Reputation: 39
You can dynamically build predicate and combine with And() Or() in using PredicateBuilder. Take a look at : http://www.albahari.com/nutshell/predicatebuilder.aspx
Upvotes: 0