No tienes acceso a esta clase

隆Contin煤a aprendiendo! 脷nete y comienza a potenciar tu carrera

Operadores OrderBy y OrderByDescending

13/26
Recursos

Aportes 13

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 鈥渓ibrosDeCategoria(string categoria)鈥 y se enviar铆a 鈥減ython鈥 la primera vez y 鈥渏ava鈥 la segunda. ImprimirValores(queries.librosDeCategoria(鈥減ython鈥) y luego ImprimirValores(queries.librosDeCategoria(鈥渏ava鈥)

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();
}
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
锘縇inqQueries 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(鈥淛ava鈥)orderby b.Title select b).ToList() ;
}