2009-05-25 1 views
1

이 쿼리에서는 항상 '일반'형식 요소를 원합니다.
_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#을 구입하고 구매하면 훨씬 더 빠르게 이해할 수 있습니다.