0% found this document useful (0 votes)
15 views

Sorting Entities: Ienumerable

The document discusses how LINQ can be used to sort collections of entities. It provides two examples of sorting a collection of books by publisher name descending, and then by title to get an ordered IEnumerable of books. Alternative code is shown using lambda expressions and method chaining to sort the collection in the same way. Sorting entities by related entity properties, like publisher name on books, is useful for complex entity relationships.

Uploaded by

jhansi rani
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Sorting Entities: Ienumerable

The document discusses how LINQ can be used to sort collections of entities. It provides two examples of sorting a collection of books by publisher name descending, and then by title to get an ordered IEnumerable of books. Alternative code is shown using lambda expressions and method chaining to sort the collection in the same way. Sorting entities by related entity properties, like publisher name on books, is useful for complex entity relationships.

Uploaded by

jhansi rani
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

Sorting entities

Using LINQ, developers can sort entities within a collection. The following code shows how you can take a collection of
books, order elements by book publisher name and then by title, and select books in an ordered collection. As a result of the
query, you will get an IEnumerable<Book> collection sorted by book publishers and titles.

Hide   Copy Code

Book[] books = SampleData.Books;


IEnumerable<Book> booksByTitle = from b in books
orderby b.Publisher.Name descending, b.Title
select b;

foreach (Book book in booksByTitle)


Console.WriteLine("Book - {0}\t-\tPublisher: {1} ",
book.Title, book.Publisher.Name );

Alternative code using functions is shown in the following example:

Hide   Copy Code

Book[] books = SampleData.Books;


IEnumerable<Book> booksByTitle = books.OrderByDescending(book=>book.Publisher.Name)
.ThenBy(book=>book.Title);

foreach (Book book in booksByTitle)


Console.WriteLine("Book - {0}\t-\tPublisher: {1} ",
book.Title, book.Publisher.Name );

This type of queries is useful if you have complex structures where you will need to order an entity using the property of a
related entity (in this example, books are ordered by publisher name field which is not placed in the book class at all).

Filtering entities / Restriction

You might also like