Can someone explain to me how this works
I dont understand how this line works:
XElement elemento = docxml.Descendants("Cliente").FirstOrDefault(x => Convert.ToInt32(x.Element("DNI").Value) == cliente.dni); This is how the xml file looks like:
XElement elemento = docxml.Descendants("Cliente").FirstOrDefault(x => Convert.ToInt32(x.Element("DNI").Value) == cliente.dni); This is how the xml file looks like:
15 Replies
it's getting the first descendant named "Cliente" where the integer value of the "DNI" element equals whatever is in
cliente.dni
so if cliente.dni
was 45868900
the XElement would contain this portion of the xml
so
descendant takes all the elements?
inside Cliente?
it gives you every sub-element in the tree, so it will give you Cliente, Nombre, Apellido, etc
which honestly seems inefficient for what it's being used for, based on your data you should just be checking direct children of Clientes
how
and how does this work
use
Elements()
instead of Descendants()
iircFirstOrDefault(x => Convert.ToInt32(x.Element("DNI").Value) == cliente.dni);
whats x
FirstOrDefault is LINQ, which is part of a collection of functions that help you filter/etc sets of data
so here
x => Convert.ToInt32(x.Element("DNI").Value) == cliente.dni
is an anonymous function (or lambda) that takes in an x
(the type is inferred from the type of the collection) and returns a bool
it calls that function for every element in the collection provided by docxml.Descendants("Cliente")
and returns the first element in the collection where that function returns true
hmm ok
so i dont need to declare the variable x right?
its just part of the syntax
it is being declared as part of the lambda definition
that part of the code is the same as if you wrote a method like
with some extra magic to actually get the value of cliente.dni in the method (called a capture)
hmm alright i think im getting it
ty
one last question tho
if i remove the FirstOrDefault thing
does it delete all the descendants from clients with the cliente.dni ?
it won't compile
XElement elemento
can only hold one element, docxml.Descendants("Cliente")
is a collection of multiple elementsthat makes sense
can i use like a foreach(xElement element in docxml.Descendants("Cliente"){}
or something like that?
or how do i get all the Cliente with the same dni
you could do that, keep in mind it will give you every element at any level so if you have Cliente elements nested inside each other you'll get all of them
u mean id be getting "Nombre" and "Apellido" as elements as well?
no because you're filtering descendants by name