Sobes.tech
Middle

Fornisci un esempio di codice che restituisce un oggetto dell'interfaccia IQueryable.

sobes.tech AI

Risposta dell'AI

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 }
    };

    // Il metodo restituisce IQueryable<Product>, consentendo di posticipare l'esecuzione della query.
    public IQueryable<Product> GetQueryableProducts()
    {
        return _products.AsQueryable(); // AsQueryable() converte IEnumerable in IQueryable
    }
}

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

        // Aggiunta di una condizione di filtro a IQueryable.
        // La query non viene ancora eseguita in questa fase.
        IQueryable<Product> filteredQuery = query.Where(p => p.Price > 100.00m);

        // Esecuzione della query al momento della materializzazione (ad esempio, chiamando ToList()).
        // Qui viene eseguita la query sulla fonte di dati (in questo caso, _products).
        List<Product> expensiveProducts = filteredQuery.ToList();

        Console.WriteLine("Prodotti costosi (Prezzo > $100):");
        foreach (var product in expensiveProducts)
        {
            Console.WriteLine($"- {product.Name} (${product.Price})");
        }

        Console.ReadKey();
    }
}