Select Last N elements using LINQ to XML

Here’s a simple example of selecting the last ‘N’ elements of a XML document using LINQ to XML

Consider the following XML

image

In order to select the last two elements, use the IEnumerable<XElement>.Reverse() which inverts the order of the elements in a sequence, and use Take(2) to return 2 elements, as shown in the following code:

static void Main(string[] args)
{
// code from DevCurry.com

XDocument xDoc = XDocument.Load("..\\..\\School.xml");
var students = xDoc.Descendants("Class").Reverse().Take(2);
foreach (var student in students)
Console.WriteLine(student.Element("Student").Value +
" " + student.Element("Name").Value);
Console.ReadLine();
}

OUTPUT

image






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: