07 Feb 2024




Intermediate

Examples for IEnumerable and IQueryable interface:

Examples using IEnumerable:

  • Filtering with LINQ to Objects:
IEnumerable<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
IEnumerable<int> evenNumbers = numbers.Where(n => n % 2 == 0);
  • Projection with LINQ to Objects:
IEnumerable<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
IEnumerable<string> numberStrings = numbers.Select(n => n.ToString());
  • Aggregation with LINQ to Objects:
IEnumerable<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
int sum = numbers.Sum();
  • Iteration with foreach:
IEnumerable<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
foreach (int number in numbers)
{
    Console.WriteLine(number);
}
  • Custom Query using LINQ to Objects:
IEnumerable<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
IEnumerable<int> squaredNumbers = numbers.Select(n => n * n);

Examples using IQueryable:

  • Filtering with LINQ to Entities (EF Core):
IQueryable<Product> products = dbContext.Products;
IQueryable<Product> expensiveProducts = products.Where(p => p.Price > 100);
  • Projection with LINQ to Entities (EF Core):
IQueryable<Product> products = dbContext.Products;
IQueryable<string> productNames = products.Select(p => p.Name);
  • Aggregation with LINQ to Entities (EF Core):
IQueryable<Product> products = dbContext.Products;
decimal totalSales = products.Sum(p => p.Price * p.QuantitySold);
  • Deferred Execution with LINQ to SQL:
IQueryable<Customer> customers = dbContext.Customers;
var query = customers.Where(c => c.Country == "USA");
var filteredCustomers = query.ToList(); // Executes the query here
  • Combining Queries with LINQ to SQL:
IQueryable<Product> products = dbContext.Products;
IQueryable<Product> discountedProducts = products.Where(p => p.Discount > 0).OrderBy(p => p.Price);
c-sharp
ienumerable
iqueryable
example