How to determine if an element exists using a lambda expression in C #?

I use the try / catch statement to check if an element exists when I parse it. Obviously, this is not the best way to do this. I use LINQ (lambda expressions) for most of my parsing, but I just don't know how to determine if an element is or not.

One big problem with some of the solutions I discovered is that they take 3-4 times as much code as using a try / catch block, which hits the target.

I would suggest that the code would look something like this:

if(document.Element("myElement").Exists())
{
   var myValue = document.Element("myElement").Value;
}

I found the link, but the loop is not needed in my case, since I can guarantee that it will be displayed only once if it exists. In addition, you need to create a dummy element, which also seems unnecessary. This doesn't seem to be the best way (or a good way) to check. Any ideas?

+5
source share
4 answers
XElement e = document.Element("myElement");
if (e != null)
{
    var myValue = e.Value; 
}

http://msdn.microsoft.com/en-us/library/system.xml.linq.xcontainer.element.aspx

"Gets the first (in the order of the document) child with the specified XName."

"Returns Nothing if there is no element with the specified name."

+4
source

Any () is a Linq command.

Assert.IsFalse( new [] { 1, 2, 3, 4 }.Any( i => i == 5 ));
0
source

Btw, "try/catch" , . , . Release , "Debug" . , "try/catch" .

Btw, №2: ", !" (TDA) " " (OCP) , "if (! (Fp = fopen (...))". "try/catch" , . OCP , (, , stdio).

OCP, TDA ? . "fopen", , Zero? "fopen" ? , , . . - . , : . , . ? , "fopen" . . Dot. "fopen" , .

: (KIS). " " , , . , , , (TDA). , SLA.

, , . , . (, ), , , "".

0

Any() - , .

If you need to make sure the item is unique, you need to do something like .Count() == 1. Alternatively, you can implement your own extension method, but it will be just a wrapper around .Count == 1.

-1
source

All Articles