Datasheet

Klein c01.tex V3 - 12/13/2007 1:48pm Page 13
Chapter 1: Project LINQ
Here are the results of this code:
<
Employee
>
<
FirstName
>
Scott
<
/FirstName
>
<
LastName
>
Klein
<
/LastName
>
<
/Employee
>
You’ll notice the use of
var
in the previous example. The
var
keyword tells the compiler to infer the type
of the variable from the expression on the right side of the statement. The
var
keyword will be discussed
in detail in Chapter 2, ‘‘A Look at Visual Studio 2008’’.
Also notice in the previous example how much easier the code is to read. The code actually follows the
structure of an XML document, so you can see what the resulting XML document will look like.
The next example uses the
XAttribute
type to add an attribute to the XML:
var x = new XElement("Employee",
new XAttribute("EmployeeID", "15"),
new XElement("FirstName", "Scott"),
new XElement("LastName","Klein"));
var s - x.ToString();
And here are the results from it:
<
Employee Employee="15"
>
<
FirstName
>
Scott
<
/FirstName
>
<
LastName
>
Klein
<
/LastName
>
<
/Employee
>
While the capability to easily define the contents of the XML is cool, the real power comes from the
ability to pass an argument that is not user-defined but in reality comes from an outside source, such as
a query, which can be enumerated and turned into XML via the standard query operators. For example,
the following takes the array of names from the first example and uses that as the source of the query for
which to construct XML:
string [] firstnames = { "Scott", "Steve", "Ken", "Joe", "John",
"Alex", "Chuck", "Sarah"};
var r = new XElement("Friends",
from fn in firstnames
where fn.StartsWith("S")
select new XElement("Name", fn))
textbox1.Text = rToString();
Here are the results from this code:
<
Friends
>
<
Name
>
Scott
<
/Name
>
<
Name
>
Steve
<
/Name
>
<
Name
>
Sarah
<
/Name
>
<
/Friends
>
13