Search code examples
c#linq

Efficent way List order by element index


I have a List of Books which below :

List<book> books = new List<book>() 
{ 
    new() { bookName = "wingbook" }, 
    new() { bookName = "Peter Pan" },
    new() { bookName = "Apple Pie" },
    new() { bookName = "Zebra" } 
}

I want to find way to order by books by index descending order (not a book name). Expected result is

result = {
    { bookName = "Zebra" },
    { bookName = "Apple Pie" },
    { bookName = "Peter Pan" },
    { bookName = "wingbook" }
}

Can I know how to write it simplified it ?


Solution

  • You simply want to reverse the list? Then use:

    books.Reverse();
    

    or you could use the Reverse extension method, that does not modify the original collection:

    var ordered = books.AsEnumerable().Reverse();
    

    You could also use the Select overload to get the index:

    books = books 
        .Select((book, index) => (book, index))
        .OrderByDescending(x => x.index)
        .Select(x => x.book)
        .ToList();