pingve
pingve

Reputation: 67

LINQ to XML in C# where clause

I`ve got a piece in xml:

<result index="0" status="0">
          <test field="aaa">value_a</test>
          <test field="bbb">value_b</test>
          <one>
            <name></name>
            <res1></res1>
          </one>
          <two>
            <name></name>
            <res2></res2>
          </two>
          <answer></answer>
          <error></error>
        </result>

var rez = from item in doc.Descendants("result")
                          where 


                          select item;

                foreach (var item in rez)
                {
                    item.Element("res1").SetValue(x);
                    item.Element("res2").SetValue(y);
                }

What do i write inside "where" to select an item ("result" block) where element "test" with attribute "aaa" has value_a, AND element "test" with an attribute "bbb" has value_b

Upvotes: 0

Views: 3641

Answers (2)

jdasilva
jdasilva

Reputation: 616

There's a few different possibilities, but I chose to pull out the value pairs for clarity and maybe a slight performance improvement. If the # of test elements was high you could make testPairs a dictionary.

var rez = from item in doc.Descendants("result")
            let testPairs = item.Elements("test")
                .Select(t => Tuple.Create((string)t.Attribute("field"), (string)t)).ToArray()
            where
                testPairs.Any(t => t.Item1=="aaa" && t.Item2=="value_a") &&
                testPairs.Any(t => t.Item1=="bbb" && t.Item2=="value_b")
            select item;

Upvotes: 1

V4Vendetta
V4Vendetta

Reputation: 38210

I am not sure probably this is what you mean

where item.Element("test").Value == "something" 
&& item.Element("test").Attribute("field").Value =="aaa"

Upvotes: 0

Related Questions