Sobes.tech
Middle

Forneça um exemplo de código que retorne um objeto da interface IQueryable.

sobes.tech IA

Resposta da IA

using System;
using System.Linq;
using System.Collections.Generic;

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

public class ProductRepository
{
    private List<Product> _products = new List<Product>
    {
        new Product { Id = 1, Name = "Laptop", Price = 1200.00m },
        new Product { Id = 2, Name = "Keyboard", Price = 75.00m },
        new Product { Id = 3, Name = "Mouse", Price = 25.00m }
    };

    // O método devolve IQueryable<Product>, permitindo adiar a execução da consulta.
    public IQueryable<Product> GetQueryableProducts()
    {
        return _products.AsQueryable(); // AsQueryable() converte IEnumerable em IQueryable
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        var repository = new ProductRepository();
        
        // Obtenção de IQueryable<Product>
        IQueryable<Product> query = repository.GetQueryableProducts();

        // Adicionando condição de filtragem ao IQueryable.
        // A consulta ainda não é executada neste ponto.
        IQueryable<Product> filteredQuery = query.Where(p => p.Price > 100.00m);

        // Executa a consulta ao materializar (por exemplo, ao chamar ToList()).
        // Aqui ocorre a consulta à fonte de dados (neste caso, _products).
        List<Product> expensiveProducts = filteredQuery.ToList();

        Console.WriteLine("Produtos caros (Preço > $100):");
        foreach (var product in expensiveProducts)
        {
            Console.WriteLine($"- {product.Name} (${product.Price})");
        }

        Console.ReadKey();
    }
}