On Oct 1, 12:32 pm, CSharper <cshar...@gmx.comwrote:
Quote:
I have following XML
<root>
<Person id="1">
<Name>a</Name>
</Person>
<Person id="2">
<Name>b</Name>
</Person>
</root>
>
I am trying to find the person with id = 1 and I use the following
>
var people =
doc.Decendents().Elements("Person").Where(s=>s.Att ribute("id").Value.Equals("1"));
>
When I run I get an empty list but when I change this to pure linq
>
var people = from c in doc.Decendents().Elements("Person")
where c.Attributes().Count() 0
&& c.Attribute("id") != null
&& c.Attribute("id").Value.Equals("1")
select c;
>
This one does return me the first note.
>
I have two questions here;
>
Is it possible to include all these && conditions in the Lambda
(stupid question) since most of all the examples I have seen are one
liners. Also what is the difference between the lambda and linq in
this selection that doesn't return the value? One side note, which is
the good way to code, lambda or linq? I see the benefits of linq but
for an untrained eye lambda could be confusing.
>
Thanks.
That can't be your actual code, because there is no method called
"Decendents" in the XDocument class. That must be a typo.
In any event, I ran the following code:
static void Main(string[] args) {
var xml = new XElement("root",
new XElement("Person",
new XAttribute("id", "1"),
new XElement("Name", "a")),
new XElement("Person",
new XAttribute("id", "2"),
new XElement("Name", "b")));
XDocument doc = new XDocument();
doc.Add(xml);
var people1 = doc.Descendants().Elements("Person").Where(s
=s.Attribute("id").Value.Equals("1"));
foreach (XElement element in people1) {
Console.WriteLine(element.ToString());
}
Console.WriteLine();
var people2 = from c in
doc.Descendants().Elements("Person")
where c.Attributes().Count() 0
&& c.Attribute("id") != null
&& c.Attribute("id").Value.Equals("1")
select c;
foreach (XElement element in people2) {
Console.WriteLine(element.ToString());
}
Console.WriteLine();
Console.WriteLine("Press ENTER to exit");
Console.ReadLine();
}
With the following results:
<Person id="1">
<Name>a</Name>
</Person>
<Person id="1">
<Name>a</Name>
</Person>
Press ENTER to exit
So it appears to work correctly to me. Either you've got a typo
somewhere in your code or your xml does not match what you are showing
us.
Can you supply a small, but complete code example that duplicates the
problem?
Chris
Chris