Elements("Employee")
where (int) emp.Attribute("id") == 2
select emp).First();
Notice that this example also uses the First() method. Why? What if your XML document had an
attribute of Dept for each employee, and your XML document had multiple employees with the same
department? The First() method helps make sure you grab the first employee thatmatches the criterion.
The query expression returns a sequence, and the First() method explicitly returns the first member of
that sequence.
The following example does the same, but uses the ElementAt() method:
XElement empnum2 = (from emp in employees.Elements("Employee")
where (int) emp.Attribute("id") == 2
select emp).ElementAt(0);
This next example digs a little deeper. It returns the values of all the Name elements for each employee. It
uses the Descendants() method to return a collection of all the descendants for the selected element.
IEnumerable
empNames =
from emp in employees.Descendants("Name")
orderby emp.Value
select emp.Value;
134
Chapter 6: Programming with LINQ to XML
foreach (string name in empNames)
listbox1.
Pages:
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241