Middle
Provide an example of code execution that returns an object of the IQueryable interface.
sobes.tech AI
Answer from AI
using System;
using System.Collections.Generic;
using System.Linq;
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public static class ProductService
{
public static IQueryable<Product> GetProducts()
{
// Simulate a data source, e.g., a database
// In a real application, this could be a DbSet from Entity Framework
var products = new List<Product>
{
new Product { Id = 1, Name = "Laptop", Price = 1200.00m },
new Product { Id = 2, Name = "Mouse", Price = 25.00m },
new Product { Id = 3, Name = "Keyboard", Price = 75.00m },
new Product { Id = 4, Name = "Monitor", Price = 300.00m },
}.AsQueryable(); // Convert IEnumerable to IQueryable
return products;
}
public static void Main(string[] args)
{
// Get IQueryable
IQueryable<Product> queryableProducts = GetProducts();
// Add filtering and sorting, which will be executed LAZILY
// during data materialization (e.g., when calling ToList() or foreach)
var expensiveProducts = queryableProducts
.Where(p => p.Price > 100m)
.OrderBy(p => p.Name);
// At this point, the query has not been executed yet.
Console.WriteLine("Query formed, but not yet executed.");
// Data materialization - executing the query against the source
Console.WriteLine("Executing query:");
foreach (var product in expensiveProducts)
{
Console.WriteLine($"- Id: {product.Id}, Name: {product.Name}, Price: {product.Price:C2}");
}
// Example of another materialization
var productList = expensiveProducts.ToList(); // Query executes again if not cached
Console.WriteLine($"\nNumber of expensive products: {productList.Count}");
}
}