No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Operadores OrderBy y OrderByDescending

13/26
Recursos

Aportes 17

Preguntas 3

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

Sana Sugerencia: Importante para tener en cuenta en lo de las Escuelas: Alumno que venga del curso de programación, luego C#, luego este, se encuentra con malas prácticas de programación al no usar parámetros en los métodos.
Ya existe un método que se llamaría “librosDeCategoria(string categoria)” y se enviaría “python” la primera vez y “java” la segunda. ImprimirValores(queries.librosDeCategoria(“python”) y luego ImprimirValores(queries.librosDeCategoria(“java”)

Operadores OrderBy y OrderByDescending

Nos permiten ordenar una colección usando cualquier criterio.

public List<Book>getByPagesOrderByDescendingQuery(IEnumerable<Book> books,int pages){
return (from b in books where b.PageCount > pages orderby b.PageCount descending select b).ToList();
}

public List<Book>getByPagesOrferByDescendingMethod(IEnumerable<Book> books,int pages){
    return books.Where(b=>b.PageCount > pages).OrderByDescending(b=>b.PageCount).ToList();
}
yo los ordene por Title =) ` public IEnumerable<Book> LibrosMasDe450PaginasDescendente()` ` {` ` return librosCollection.Where(p => p.PageCount > 450).OrderByDescending(t => t.Title);` ` }`
```txt //OrderBy //Extension method return BooksCollections.Where(p => p.Categories.Contains("Java")).OrderBy(p => p.Title); //Query expression var query = from p in BooksCollections where p.Categories.Contains("Java") orderby p.Title select p; return query; //OrderByDescending //Extension method return BooksCollections.Where(p => p.PageCount > 450).OrderByDescending(p => p.PageCount); //Query expression var query = from p in BooksCollections where p.PageCount > 450 orderby p.PageCount descending select p; return query; ```
Aquí mi aporte sobre cómo resolver el reto 2 por el método query y elextensión: ```js //Extension Method return booksCollection.Where(x => x.pageCount > 450).OrderByDescending(p => p.pageCount); //Query Method return from books in booksCollection where books.pageCount > 450 orderby books.pageCount descending select books; ``` //Extension Method return booksCollection.Where(x => x.pageCount > 450).OrderByDescending(p => p.pageCount); //Query Method return from books in booksCollection where books.pageCount > 450 orderby books.pageCount descending select books;
```js public IEnumerable<Book> orderByDescLibrosmay450pag() { return librosCollection.Where(p => p.PageCount > 450). OrderByDescending(p => p.PageCount); } ```
```js public IEnumerable<Book> orderByCategoryJava() { return librosCollection.Where(p => p.Categories.Contains("Java")).OrderBy(p => p.Title); } ```
Añadí parámetros para ver qué tal quedaba y no se ve tan mal. Ni idea si sea mejor de X o Y manera: **Program.cs** `// Ordenador de manera descendente todos los libros con más de 450 páginas` `var librosConMas450 = queries.LibrosConXMasPaginas(450);` `PrintValues(queries.LibrosPorNombreDescendente(librosConMas450));` **LinqQueries.cs** `public IEnumerable<Book> LibrosConXMasPaginas(int maxPages, List<Book> libros = null)` `{` ` // we making the program scalable ` ` if(libros == null)` ` {` ` libros = librosCollection;` ` }` ` // extension method` ` return libros.Where(p => p.PageCount > maxPages);` ` // query expression` ` //return from l in libros where l.PageCount > maxPages select l;` `}` `public IEnumerable<Book> LibrosPorNombreDescendente(IEnumerable<Book> libros = null)` `{` ` if (libros == null)` ` libros = librosCollection;` ` return libros.OrderByDescending(p => p.Title);` `}`
<code> 
using Linq;

LinqQueries queries = new();

// Inicializamos el filter y el orderBy
Func<Book, bool> filter = b => b.Title != null;
Func<Book, IComparable> orderBy = b => b.PublishedDate.Year;

filter = b => b.PageCount > 450;
orderBy = b => b.PageCount;

PrintValues(queries.GetBooksFromQuery(filter, orderBy, false));

void PrintValues(IEnumerable<Book> books)
{
    Console.WriteLine("{0,-60}| {1, 10}| {2, 11}\n", "Titulo", "N. Paginas", "Fecha publicacion");
    foreach (var book in books)
    {
        Console.WriteLine("{0,-60}| {1, 10}| {2, 11}", book.Title, book.PageCount, book.PublishedDate.ToShortDateString());
    }
    Console.WriteLine($"\nTotal libros: {books.ToList().Count}");
}

using System.Text.Json;

namespace Linq;

public class LinqQueries
{
    private List<Book> Books = new();
    public LinqQueries()
    {
        using (StreamReader reader = new StreamReader("books.json"))
        {
            string json = reader.ReadToEnd();
            Books = JsonSerializer.Deserialize<List<Book>>(json, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true })!;
        }
    }

    public IEnumerable<Book> GetAllBooks() => Books;

    public IEnumerable<Book> BooksAfter2000() =>
        Books.Where(b => b.PublishedDate.Year > 2000).OrderBy(b => b.PublishedDate.Year);

    public IEnumerable<Book> GetBooksFromQuery(Func<Book, bool> filter, Func<Book, IComparable> orderBy)
        => Books.Where(filter).OrderBy(orderBy);

    public IEnumerable<Book> GetBooksFromQuery(Func<Book, bool> filter, Func<Book, IComparable> orderBy, bool ascending)
    {
        var books = Books.Where(filter);
        return ascending ? books.OrderBy(orderBy) : books.OrderByDescending(orderBy);
    }
}

Desde mi punto de vista estas deben ser las implementaciones usando linq:

public IEnumerable<Book> GetBooksFilteredByCategoryAndSortedByTitle(string category)
    {
        //extension method
        // return CollectionBook.Where(book => (book.Categories ?? Enumerable.Empty<String>()).Contains(category)).OrderBy(book => book.Title);

        //linq query
        return from book in CollectionBook where book.Categories.Contains(category) orderby book.Title select book;
    }

    public IEnumerable<Book> GetBooksByPagesAndSortedDescending(int pages)
    {
        //extension method
        // return CollectionBook.Where(book => (book.PageCount ?? 0) > pages).OrderByDescending(book => book.PageCount);

        //linq query
        return from book in CollectionBook where book.PageCount > pages orderby book.PageCount descending select book;
    }

query con c# y linq:

public IEnumerable<Book> LibrosMasDeXPaginasDescendente(int pages)
        {
            return librosCollection.Where(book => book.PageCount > pages).OrderByDescending(book => book.PageCount);
        }

usando el método:

//* Libros de Java - Ordenados por nombre descendente
        ImprimirValores(queries.LibrosMasDeXPaginasDescendente(450));

output:
Titulo N. Paginas Fecha publicacion

JavaScript: The Definitive Guide 706 06/06/2020
Python and Tkinter Programming 688 01/01/2000
GWT in Action 632 01/06/2007
Android in Action, Second Edition 592 14/01/2011
Flexible Rails 592 01/01/2008
OSGi in Action 576 06/04/2011
Up to Speed with Swing, Second Edition 560 01/10/1999
Brownfield Application Development in .NET 550 16/04/2010
Pool and DBCP: Creating and Using Object Pools 521 01/03/2005
Grails in Action 520 01/05/2009
Distributed Application Development with PowerBuilder 6.0 504 01/06/1998

using System.Security.Cryptography.X509Certificates;
using System.Linq;


public class LinqQueries
{

    private List<Book> librosCollection = new List<Book>();

    public LinqQueries()
    {
        using(StreamReader reader = new StreamReader("books.json"))
        {
            string json = reader.ReadToEnd();
            this.librosCollection = System.Text.Json.JsonSerializer.Deserialize<List<Book>>(json, new System.Text.Json.JsonSerializerOptions() {PropertyNameCaseInsensitive = true});
        }
    }

    public IEnumerable<Book> TodaLaColeccion()
    {
        return librosCollection;
    }

    public IEnumerable<Book> ListaLibrosDespues2000()
    {
         // ---> Extension method
        //return this.librosCollection.Where(lib => lib.PublishedDate.Year > 2000);


        // ---> Extension spresion
        return from list in this.librosCollection where list.PublishedDate.Year > 2000 select list;
    }

    public IEnumerable<Book> ListaLibrosMasd250PagConPalabrasInAction()
    {
        // ---> Extension method
        //return this.librosCollection.Where(p => p.PageCount > 250 && p.Title.Contains("in Action"));

        // ---> Extension method
        return from lista in this.librosCollection where lista.PageCount > 250 && lista.Title.Contains("in Action") select lista;

    }
 
    public bool TodosLibrosTienenStatus()
    {
        return librosCollection.All(x => x.Status != string.Empty);
    }

    public bool TodosLibrosPublicadosAnio2005()
    {
        return librosCollection.Any(x => x.PublishedDate.Year > 2005);
    }

    public IEnumerable<Book> CategoriasMicrosoft()
    {
        return librosCollection.Where(x => x.Categories.Contains("Microsoft .NET"));
    }

    public IEnumerable<Book> CategoriasJava()
    {
        return librosCollection.Where(x => x.Categories.Contains("Java")).OrderBy(x => x.Title);
    }

    public IEnumerable<Book> TodosLibrosMasd450Pag()
    {
        return librosCollection.Where(x => x.PageCount > 450).OrderByDescending(x => x.PageCount);
    }

}
using System.Xml.Serialization;
using System.Net.Mime;
// See https://aka.ms/new-console-template for more information
LinqQueries queries = new LinqQueries();

//ImprimirValores(queries.TodaLaColeccion());
//ImprimirValores(queries.ListaLibrosDespues2000());

// LIBROS QUE TIENE MAS DE 250 PAG Y TIENE EN EL TITULO LA PALABRAS IN ACTION
//ImprimirValores(queries.ListaLibrosMasd250PagConPalabrasInAction());

Console.WriteLine($"{queries.TodosLibrosTienenStatus()}");

Console.WriteLine("=====================================");

Console.WriteLine($"{queries.TodosLibrosPublicadosAnio2005()}");

Console.WriteLine("=====================================");

ImprimirValores(queries.CategoriasMicrosoft());

Console.WriteLine("=====================================");

ImprimirValores(queries.CategoriasJava());

Console.WriteLine("=====================================");

ImprimirValores(queries.TodosLibrosMasd450Pag());

void ImprimirValores(IEnumerable<Book> listadelibros)
{
    Console.WriteLine("{0,-60} {1, 15} {2, 15}\n", "Titulo", "N. Paginas", "Fecha publicacion");
    foreach(var item in listadelibros)
    {
        Console.WriteLine("{0,-60} {1, 15} {2, 15}", item.Title, item.PageCount, item.PublishedDate.ToShortDateString());
    }
}```



Con query expresion sería asi:

public IEnumerable<Book> BooksJavaForName(){
   return (from b in librosCollection where b.Categories.Contains("Java") orderby b.Title select b);
}

public IEnumerable<Book> BooksMajor450Pages(){
   return from b in librosCollection where b.PageCount > 450 orderby b.PageCount descending select b;
}

public List<Book> getByCategoryOrderBy(IEnumerable<Book> books){
return (from b in books where b.Categories.Contains(“Java”)orderby b.Title select b).ToList() ;
}

```js public IEnumerable <Book> JavaBooksAsc() { //Extension Method //return booksCollection.Where(p => p.Categories.Contains("Java")).OrderBy(p => p.Title); //QueryExpression return from b in booksCollection where b.Categories.Contains("Java") orderby b.Title select b; } public IEnumerable<Book> MoreThan450PagsDesc() { //Extension Method //return booksCollection.Where(p => p.PageCount > 450).OrderByDescending(p => p.PageCount); // Query Expresion return from b in booksCollection where b.PageCount > 450 orderby b.PageCount descending select b; } ```
Mi aporte, reusando la funcion de filtrado por categoria: ```c# public IEnumerable<Book> OrderPorNombreBuscandoEnCategoria(string cat, bool desc = false){ var libros = ContainsInCategory(cat); if (!desc) return libros.OrderBy(l=>l.Title); else return libros.OrderByDescending(l=>l.Title); } public IEnumerable<Book> OrdenPorPaginasConMasPaginasQue(int num, bool desc = false){ var libros = _librosCollection.Where(libros=>libros.PageCount >= num); if (!desc) return libros.OrderBy(l=>l.PageCount); else return libros.OrderByDescending(l=>l.PageCount); } ```