Middle
Navedite primer koda koji vraća objekat interfejsa IQueryable.
sobes.tech АИ
Одговор од АИ
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 }
};
// Метод връща IQueryable<Product>, който позволява отлагане на изпълнението на заявката.
public IQueryable<Product> GetQueryableProducts()
{
return _products.AsQueryable(); // AsQueryable() преобразува IEnumerable в IQueryable
}
}
public class Program
{
public static void Main(string[] args)
{
var repository = new ProductRepository();
// Получаване на IQueryable<Product>
IQueryable<Product> query = repository.GetQueryableProducts();
// Добавяне на условие за филтриране към IQueryable.
// Заявката все още не е изпълнена на този етап.
IQueryable<Product> filteredQuery = query.Where(p => p.Price > 100.00m);
// Изпълнение на заявката при материализация (например, при извикване на ToList()).
// Тук се извършва заявка към източника на данни (в този случай, към _products).
List<Product> expensiveProducts = filteredQuery.ToList();
Console.WriteLine("Скъпи продукти (Цена > $100):");
foreach (var product in expensiveProducts)
{
Console.WriteLine($"- {product.Name} (${product.Price})");
}
Console.ReadKey();
}
}