Построение предложения where в запросе Linq - PullRequest
1 голос
/ 25 мая 2009

В этом запросе я всегда хочу элемент «нормального» типа.
Если установлен флаг _includeX, мне также нужны элементы типа «рабочее пространство».
Есть ли способ написать это как один запрос? Или создать предложение where на основе _includeX перед отправкой запроса?

    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 Ответ

1 голос
/ 25 мая 2009

Вы можете разбить его на отдельный предикат:

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 # в глубине, и все это будет иметь смысл намного быстрее, чем изучение этого материала постепенно ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...