Sobes.tech
Middle

Andke näide koodist, mis tagastab IQueryable liidese objekti.

sobes.tech AI

Vastus AI-lt

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

    // Meetod tagastab IQueryable<Product>, mis võimaldab päringut edasi lükata.
    public IQueryable<Product> GetQueryableProducts()
    {
        return _products.AsQueryable(); // AsQueryable() muudab IEnumerable IQueryable-ks
    }
}

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

        // Lisage filtritingimust IQueryable-ile.
        // Päring ei ole veel täidetud.
        IQueryable<Product> filteredQuery = query.Where(p => p.Price > 100.00m);

        // Päring täidetakse ainult siis, kui see materialiseerub (nt. ToList() kasutades).
        // Siin toimub päring andmeallikale (antud juhul, _products).
        List<Product> expensiveProducts = filteredQuery.ToList();

        Console.WriteLine("Kallid tooted (Hind > $100):");
        foreach (var product in expensiveProducts)
        {
            Console.WriteLine($"- {product.Name} (${product.Price})");
        }

        Console.ReadKey();
    }
}