2012-10-31 89 views
0

我想編寫一個動態LINQ查詢,它根據兩個時間幀startTime和errorTime來檢查'where'條件。 本代碼是在這裏,在動態LINQ中添加條件

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; 

} 

我能知道如何只有一個查詢,以便我可以把開始時間和動態errortime得到的結果?

回答

2

你可以把它的動態調用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); 
}