簡體   English   中英

在Linq查詢中構建“ where”子句

[英]Building the 'where' clause in a Linq query

在此查詢中,我始終需要'normal'類型的元素。
如果設置了_includeX標志,我也需要'workspace'類型的元素。
有沒有一種方法可以將其寫為一個查詢? 還是在提交查詢之前基於_includeX構建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,
        }; 
}

您可以將其分解為單獨的謂詞:

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

或結合第一和​​第三,然后執行以下操作:

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#,一點一點地學習這些東西就會變得更加有意義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM