简体   繁体   English

在动态linq中添加条件

[英]Adding conditions in dynamic linq

I want to write a dynamic linq query that checks for 'where' condition based on two time frames, startTime and errorTime. 我想编写一个动态linq查询,根据两个时间帧startTime和errorTime检查“where”条件。 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? 我可以知道如何只有一个查询,以便我可以动态发送开始时间和错误的时间来获得结果吗?

You can make it dynamic by calling the where clause multiple times, based on conditions: 您可以根据条件多次调用where子句使其动态化:

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);
}

You can dynamically build predicate and combine with And() Or() in using PredicateBuilder. 您可以使用PredicateBuilder动态构建谓词并与And()或()结合使用。 Take a look at : http://www.albahari.com/nutshell/predicatebuilder.aspx 请查看: http//www.albahari.com/nutshell/predicatebuilder.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM