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



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: