0

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?

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can dynamically build predicate and combine with And() Or() in using PredicateBuilder. Take a look at : http://www.albahari.com/nutshell/predicatebuilder.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.