1

LINQ を使用して XML ファイルから値を読み取ろうとしています。通常の C#/.Net アプローチに対して LINQ を使用しようとするのは、これが初めてです。

私のXMLは次のようになります。

<Description>
<Account Green="A" White="D">House</Account>
<Account Green="B" White="D">Car</Account>
</Description>

これは私が使用している LINQexpression です。House という値、つまり属性 A と D を持つ要素を読みたいと思います。

var feeds = (from item in doc.Descendants("Description")
 from category in item.Elements("Account")                    
 let attribute = category.Attribute("Green")                    
 let xAttribute = category.Attribute("White")                    
 where attribute != null && (xAttribute != null && (xAttribute.Value == "A" 
 && attribute.Value == "D")) select item.Value).ToString();   

何が間違っているのかわかりません。どんな助けでも大歓迎です。

4

1 に答える 1

1

ここに がありIEnumerable<string>ます - ここに単一の文字列が必要なようですのでFirst()、列挙型の最初の項目の値を取得するために a を追加します。

var feeds = (from item in doc.Descendants("Description")
 from category in item.Elements("Account")                    
 let attribute = category.Attribute("Green")                    
 let xAttribute = category.Attribute("White")                    
 where attribute != null && (xAttribute != null && (xAttribute.Value == "A" 
 && attribute.Value == "D")) select category.Value).First(); 

同じことを達成するためのより簡単な方法は次のとおりです。

string result = doc.Descendants("Account")
                   .Where(x => x.Attribute("Green") != null && x.Attribute("Green").Value == "A"
                            && x.Attribute("White") != null && x.Attribute("White").Value == "D")
                   .Select(x => x.Value)
                   .First();
于 2012-04-27T21:14:51.387 に答える