2009-05-25 12 views
1

このクエリでは、いつも 'normal'型要素が必要です。
_includeXフラグが設定されている場合は、 'workspace'タイプの要素も必要です。
これを1つのクエリとして記述する方法はありますか?または、クエリを送信する前に_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, 
     }; 

OR条件をインライン:

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#を深く購入してみてください。これで少しでも素早くこのことを学ぶことができます。