2009-05-25 135 views
1

在此查詢中,我總是希望使用'normal'類型的元素。
如果設置了_includeX標誌,我也需要'工作區'類型的元素。
有沒有辦法將它寫成一個查詢?或者在提交查詢之前建立基於_includeX的where子句?在Linq查詢中構建'where'子句

if (_includeX) { 
    query = from xElem in doc.Descendants(_xString) 
     let typeAttributeValue = xElem.Attribute(_typeAttributeName).Value 
     where typeAttributeValue == _sWorkspace || 
       typeAttributeValue == _sNormal 
     select new xmlThing 
     { 
      _location = xElem.Attribute(_nameAttributeName).Value, 
      _type = xElem.Attribute(_typeAttributeName).Value, 
     }; 
} 
else { 
    query = from xElem in doc.Descendants(_xString) 
     where xElem.Attribute(_typeAttributeName).Value == _sNormal 
     select new xmlThing 
     { 
      _location = xElem.Attribute(_nameAttributeName).Value, 
      _type = xElem.Attribute(_typeAttributeName).Value, 
     }; 
} 

回答

1

你可以打破它變成一個獨立的謂語:

Predicate<string> selector = x=> _includeX 
    ? x == _sWorkspace || x == _sNormal 
    : x == _sNormal; 

query = from xElem in doc.Descendants(_xString) 
     where selector(xElem.Attribute(_typeAttributeName).Value) 
     select new xmlThing 
     { 
      _location = xElem.Attribute(_nameAttributeName).Value, 
      _type = xElem.Attribute(_typeAttributeName).Value, 
     }; 

或內聯的條件:

query = from xElem in doc.Descendants(_xString) 
    let typeAttributeValue = xElem.Attribute(_typeAttributeName).Value 
    where (typeAttributeValue == _sWorkspace && _includeX) || 
      typeAttributeValue == _sNormal 
    select new xmlThing 
    { 
     _location = xElem.Attribute(_nameAttributeName).Value, 
     _type = xElem.Attribute(_typeAttributeName).Value, 
    }; 

或者刪除查詢表達式使用和這樣來做: -

var all = doc.Descendants(_xString); 
var query = all.Where(xElem=> { 
     var typeAttributeValue = xElem.Attribute(_typeAttributeName).Value; 
     return typeAttributeValue == _sWorkspace && includeX) || typeAttributeValue == _sNormal; 
}) 
.Select(xElem => 
    select new xmlThing 
    { 
     _location = xElem.Attribute(_nameAttributeName).Value, 
     _type = xElem.Attribute(_typeAttributeName).Value, 
    }) 

或結合第一和​​第三rd和do:

Predicate<string> selector = x=> _includeX 
    ? x == _sWorkspace || x == _sNormal 
    : x == _sNormal; 

query = doc.Descendants(_xString) 
     .Where(xElem => selector(xElem.Attribute(_typeAttributeName).Value)) 
     .Select(xElem => new xmlThing 
     { 
      _location = xElem.Attribute(_nameAttributeName).Value, 
      _type = xElem.Attribute(_typeAttributeName).Value, 
     };) 

這一切都取決於您的上下文中最乾淨的工作。

爲自己做個忙,併購買(並閱讀!)C#深入,這將有助於更快速地學習這個東西一點點...