1

在这个查询中,我总是想要“正常”类型的元素。
如果设置了 _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,
        }; 
}
4

1 回答 1

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

或者结合第一个和第三个并执行:

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#,一点一点地学习这些东西会更快地变得有意义......

于 2009-05-25T14:00:56.637 回答