2009-05-25 200 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#深入,这将有助于更快速地学习这个东西一点点...